Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override invalid option message with getopts in bash

Tags:

bash

shell

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?

like image 246
Afonso Matos Avatar asked Jul 04 '15 13:07

Afonso Matos


People also ask

What does getopts mean in Bash?

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.

What is getopts in 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.

Which of these is a difference between getopt and getopts?

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.


1 Answers

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
like image 86
Eugeniu Rosca Avatar answered Sep 22 '22 01:09

Eugeniu Rosca