I wrote a shell script to do something. Everything works fine! A part of my code is something like this, so that I can pass options and arguments to it:
while getopts "a:b:c" opt
do
case $opt in
a) AA=$OPTARG ;;
b) BB=$OPTARG ;;
c) CC=$OPTARG ;;
esac
done
shift $(expr $OPTIND - 1)
But now I want to add an option, say d
and I don't want it to use any argument, as the code shows below, but it ends with an error, complaining option requires an argument error -- d
It seems that getopts can't do that.
while getopts "a:b:c:d" opt
do
case $opt in
a) AA=$OPTARG ;;
b) BB=$OPTARG ;;
c) CC=$OPTARG ;;
d) DD="ON" ;;
esac
done
shift $(expr $OPTIND - 1)
What should I do then? What is the common practice if I want both option types, one can accept argument, while the other doesn't need argument?
The :
in the getopts
specifier is not a separator. From man getopts
:
if a character is followed by a colon, the option is expected to have an argument, which should be separated from it by white space.
So if you want an option which doesn't take an argument, simply add the character. If you want it to take an argument, add the character followed by :
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With