I would like to build a script with getopts, that continues in the flag, when an $OPTARG isn't set. My script looks like this:
OPTIONS=':dBhmtb:P:'
while getopts $OPTIONS OPTION
do
case "$OPTION" in
m ) echo "m"
t ) echo "t"
d ) echo "d";;
h ) echo "h";;
B ) echo "b";;
r ) echo "r";;
b ) echo "b"
P ) echo hi;;
#continue here
\? ) echo "?";;
:) echo "test -$OPTARG requieres an argument" >&2
esac
done
My aim is to continue at my comment, when there is no $OPTARG set for -P.
All I get after running ./test -P is :
test -P requieres an argument
and then it continues after the loop but I want to continue in the -P flag.
All clear?
Any Ideas?
First, fix the missing
;;
in some of the case branches.I don't think you can: you told getopts that
-P
requires an argument: two error cases-P
without an argument is the last option. In this case getops sees that nothing follows -P and sets the OPTION variable to:
, which you handle in the case statement.-P
is followed by another option: getopts will simply take the next word, even if the next word is another option, as OPTARG.Change the case branch to
Then:
bash script.sh -P -m -t
, the output isbash script.sh -Pmt
, the output isThis is clearly difficult to work around. How do you know if the user intended the option argument to be literally "mt" and not the options -m and -t?
You might be able to work around this using
getopt
(see the canonical example) using an optional argument for a long option (those require an equal sign like--long=value
) so it's maybe easier to check if the option argument is missing or not.Translating
getopts
parsing togetopt
-- it's more verbose, but you have finer-grained controlSuccessfully invoking the program with
--P
:This does impose higher overhead on your users, because
-P
(with one dash) is invalid, and the argument must be given with=