In a linux bash script, I want to have two lists of arguments: one are those started with single dash and the other those started with double dash. For example:
script -a 1 --b=3 -c 7 --d=8
Then it can return them in two group variables:
group1 : -a 1 -c 7
group2 : --b=3 --d=8
I know that $@
holds a list of all arguments. I don't know whether I should iterate them and make them distinct or there are easier solutions. This is my try:
g1=""
g2=""
for i in $@; do
echo $i
if [[ $i == --* ]]; then
g1="${g1} $i"
else
g2="${g2} $i"
fi
done
echo $g1
echo $g2
regardless of its accuracy, it says:
test.sh: 5: [[: not found
CodePudding user response:
Use a case/esac
to facilitate the option parsing instead of a ìf
. And use the shebang (#!
) to choose the shell you want to use. I also added a case to manage parameters without options:
#!/bin/sh
g1=""
g2=""
for i in $@
do
echo $i
case $i in
# -- option
--*) g1="${g1} $i"; g=1;;
# - option
-*) g2="${g2} $i"; g=2;;
# Parameter
*) p=$i
if [ "$g" = 1 ]
then
g1="${g1} $p"
g=0
elif [ "$g" = 2 ]
then
g2="${g2} $p"
g=0
else
others="$others $p"
fi
;;
esac
done
echo g1=$g1
echo g2=$g2
echo others=$others
Example of runs:
$ ./t.sh -o opt --t -h --h --p param param2
-o
opt
--t
-h
--h
--p
param
param2
g1= --t --h --p param
g2= -o opt -h
others= param2
$ ./t.sh file -o --t --p param
file
-o
--t
--p
param
g1= --t --p param
g2= -o
others= file
CodePudding user response:
You may better use shell array to hold 2 different set of arguments. With few fixes this script should address it:
g1=()
g2=()
for i; do
if [[ $i == '--'* ]]; then
g1 =( "$i" )
else
g2 =( "$i" )
fi
done
echo "group1: ${g1[@]}"
echo "group2: ${g2[@]}"
Output:
group1: --b=3 --d=8
group2: -a 1 -c 7