I have this simple bash script
if [ $# -eq 0 ]
then du
else
while getopts :d:h:s:r:f:a: option; do
case $option in
d) echo 'd';;
h) echo 'h';;
s) echo 's';;
r) echo 'r';;
f) echo 'f';;
a) echo 'a';;
\?) echo 'option invalide,-h pour obtenir I aide'
esac
done
fi
and when I call it with ./script.sh -d -a
for example I would like to get "d a" returned.
Problem is I only get "d" or "a" if I call it in the other order.
How can I do to have the script doing all present options instructions ?
CodePudding user response:
Your call to getopt
declared every option to take an argument by following each name with a :
. As such, script.sh -d -a
recognizes the -d
option with argument -a
, but you ignore the argument. The same holds for script.sh -a -d
: you recognize -a
but ignore its -d
option.
If you omit the :
s, then the options are simply flags that take no argument, and you'll see each option in turn:
while getopts :dhsrfa option; do
When you do use :
, the argument provided with the option is available in the OPTARG
parameter. Try your script with the following:
while getopts :d:h:s:r:f:a: option; do
case $option in
d) echo "d with $OPTARG";;
h) echo "h with $OPTARG";;
s) echo "s with $OPTARG";;
r) echo "r with $OPTARG";;
f) echo "f with $OPTARG";;
a) echo "a with $OPTARG";;
\?) echo 'option invalide,-h pour obtenir I aide'
esac
done
CodePudding user response:
You can pass more than one argument to your bash script. In general, here is the syntax of passing multiple arguments to any bash script:
script.sh arg1 arg2 arg3 … The second argument will be referenced by the $2 variable, the third argument is referenced by $3, .. etc.
The $0 variable contains the name of your bash script in case you were wondering!