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 ?
Your call to
getoptdeclared every option to take an argument by following each name with a:. As such,script.sh -d -arecognizes the-doption with argument-a, but you ignore the argument. The same holds forscript.sh -a -d: you recognize-abut ignore its-doption.If you omit the
:s, then the options are simply flags that take no argument, and you'll see each option in turn:When you do use
:, the argument provided with the option is available in theOPTARGparameter. Try your script with the following: