I am using getopts
to track options that are given to my script. However, I want to able to detect whether an option that was specified is invalid. I can do this, but it will always echo a message that I haven't written.
The result
my.sh: illegal option -- x
Error: Invalid option was specified --
What I want to achieve
Error: Invalid option was specified --
A snippet of my code
while getopts g:r: option; do
case $option in
g) guesses=$OPTARG;;
r) range=$OPTARG;;
?) echo "Error: Invalid option was specified -- $OPTARG";;
esac
done
How can I achieve the desired result?
Updated: 02/01/2021 by Computer Hope. On Unix-like operating systems, getopts is a builtin command of the Bash shell. It parses command options and arguments, such as those passed to a shell script.
The getopts command is a Korn/POSIX Shell built-in command that retrieves options and option-arguments from a list of parameters. An option begins with a + (plus sign) or a - (minus sign) followed by a character. An option that does not begin with either a + or a - ends the OptionString.
getopt vs getopts The main differences between getopts and getopt are as follows: getopt does not handle empty flag arguments well; getopts does. getopts is included in the Bourne shell and Bash; getopt needs to be installed separately.
Assuming you want two short options -g
and -r
, the following example will not trigger the illegal option
message on passing -x
:
while getopts ":g :r" option; do
case $option in
g) guesses=$OPTARG;;
r) range=$OPTARG;;
?) echo "Error: Invalid option was specified -$OPTARG";;
esac
done
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