Reputation: 2726
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?
Upvotes: 21
Views: 45321
Reputation: 123470
This would have happened if you had a colon after the d
in "a:b:c:d"
.
You don't have that in your code sample, and it accepts -d
with no arguments just fine.
Perhaps you took it off when writing your test case? The tag wiki step 2 for posting says to "Test your example. Make sure it runs and still shows the problem. Do not brush this off."
Upvotes: 3
Reputation: 58808
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 :
.
Upvotes: 59