Reading $OPTARG for optional flags?

99.8k views Asked by At

I'd like to be able to accept both mandatory and optional flags in my script. Here's what I have so far.

#!bin/bash

while getopts ":a:b:cdef" opt; do
      case $opt in
        a ) APPLE="$OPTARG";;
        b ) BANANA="$OPTARG";;
        c ) CHERRY="$OPTARG";;
        d ) DFRUIT="$OPTARG";;
        e ) EGGPLANT="$OPTARG";;
        f ) FIG="$OPTARG";;
        \?) echo "Invalid option: -"$OPTARG"" >&2
            exit 1;;
        : ) echo "Option -"$OPTARG" requires an argument." >&2
            exit 1;;
      esac
    done
echo "Apple is "$APPLE""
echo "Banana is "$BANANA""
echo "Cherry is "$CHERRY""
echo "Dfruit is "$DFRUIT""
echo "Eggplant is "$EGGPLANT""
echo "Fig is "$FIG""

However, the output for the following:

bash script.sh -a apple -b banana -c cherry -d dfruit -e eggplant -f fig

...outputs this:

Apple is apple
Banana is banana
Cherry is 
Dfruit is 
Eggplant is 
Fig is

As you can see, the optional flags are not pulling the arguments with $OPTARG as it does with the required flags. Is there a way to read $OPTARG on optional flags without getting rid of the neat ":)" error handling?

=======================================

EDIT: I wound up following the advice of Gilbert below. Here's what I did:

#!/bin/bash

  if [[ "$1" =~ ^((-{1,2})([Hh]$|[Hh][Ee][Ll][Pp])|)$ ]]; then
    print_usage; exit 1
  else
    while [[ $# -gt 0 ]]; do
      opt="$1"
      shift;
      current_arg="$1"
      if [[ "$current_arg" =~ ^-{1,2}.* ]]; then
        echo "WARNING: You may have left an argument blank. Double check your command." 
      fi
      case "$opt" in
        "-a"|"--apple"      ) APPLE="$1"; shift;;
        "-b"|"--banana"     ) BANANA="$1"; shift;;
        "-c"|"--cherry"     ) CHERRY="$1"; shift;;
        "-d"|"--dfruit"     ) DFRUIT="$1"; shift;;
        "-e"|"--eggplant"   ) EGGPLANT="$1"; shift;;
        "-f"|"--fig"        ) FIG="$1"; shift;;
        *                   ) echo "ERROR: Invalid option: \""$opt"\"" >&2
                              exit 1;;
      esac
    done
  fi

  if [[ "$APPLE" == "" || "$BANANA" == "" ]]; then
    echo "ERROR: Options -a and -b require arguments." >&2
    exit 1
  fi

Thanks so much, everyone. This works perfectly so far.

6

There are 6 answers

1
Gilbert On BEST ANSWER

Most shell getopts have been annoying me for a long time, including lack of support of optional arguments.

But if you are willing to use "--posix" style arguments, visit bash argument case for args in $@

0
nneonneo On

: means "takes an argument", not "mandatory argument". That is, an option character not followed by : means a flag-style option (no argument), whereas an option character followed by : means an option with an argument.

Thus, you probably want

getopts "a:b:c:d:e:f:" opt

If you want "mandatory" options (a bit of an oxymoron), you can check after argument parsing that your mandatory option values were all set.

0
Jonathan Leffler On

Understanding bash's getopts

The bash manual page (quoting the version 4.1 manual) for getopts says:

getopts optstring name[args]

getopts is used by shell scripts to parse positional parameters. optstring contains the option characters to be recognized; 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. The colon (‘:’) and question mark (‘?’) may not be used as option characters. Each time it is invoked, getopts places the next option in the shell variable name, initializing name if it does not exist, and the index of the next argument to be processed into the variable OPTIND. OPTIND is initialized to 1 each time the shell or a shell script is invoked. When an option requires an argument, getopts places that argument into the variable OPTARG. The shell does not reset OPTIND automatically; it must be manually reset between multiple calls to getopts within the same shell invocation if a new set of parameters is to be used.

When the end of options is encountered, getopts exits with a return value greater than zero. OPTIND is set to the index of the first non-option argument, and name is set to ‘?’.

getopts normally parses the positional parameters, but if more arguments are given in args, getopts parses those instead.

getopts can report errors in two ways. If the first character of optstring is a colon, silent error reporting is used. In normal operation diagnostic messages are printed when invalid options or missing option arguments are encountered. If the variable OPTERR is set to 0, no error messages will be displayed, even if the first character of optstring is not a colon.

If an invalid option is seen, getopts places ‘?’ into name and, if not silent, prints an error message and unsets OPTARG. If getopts is silent, the option character found is placed in OPTARG and no diagnostic message is printed. If a required argument is not found, and getopts is not silent, a question mark (‘?’) is placed in name, OPTARG is unset, and a diagnostic message is printed. If getopts is silent, then a colon (‘:’) is placed in name and OPTARG is set to the option character found.

Note that:

  1. The leading colon in the option string puts getopts into silent mode; it does not generate any error messages.

  2. The description doesn't mention anything about optional option arguments.

I'm assuming that you are after functionality akin to:

script -ffilename
script -f

where the flag f (-f) optionally accepts an argument. This is not supported by bash's getopts command. The POSIX function getopt() barely supports that notation. In effect, only the last option on a command line can have an optional argument under POSIX.

What are the alternatives?

In part, consult Using getopts in bash shell script to get long and short command-line options.

The GNU getopt (singular!) program is a complex beastie that supports long and short options and supports optional arguments for long options (and uses GNU getopt(3). Tracking its source is entertaining; the link on the page at die.net is wrong; you'll find it in a sub-directory under ftp://ftp.kernel.org/pub/linux/utils/util-linux (without the -ng). I've not tracked down a location at http://www.gnu.org/ or http://www.fsf.org/ that contains it.

0
AudioBubble On

It isn't easy... Any "optional" option arguments must actually be required as far as getopts will know. Of course, an optional argument must be a part of the same argument to the script as the option it goes with. Otherwise an option -f with an optional argument and an option -a with a required argument can get confused:

# Is -a an option or an argument?
./script.sh -f -a foo

# -a is definitely an argument
./script.sh -f-a foo

The only way to do this is to test whether the option and its argument are in the same argument to the script. If so, OPTARG is the argument to the option. Otherwise, OPTIND must be decremented by one. Of course, the option is now required to have an argument, meaning a character will be found when an option is missing an argument. Just use another case to determine if any options are required:

while getopts ":a:b:c:d:e:f:" opt; do
    case $opt in
        a) APPLE="$OPTARG";;
        b) BANANA="$OPTARG";;
        c|d|e|f)
            if test "$OPTARG" = "$(eval echo '$'$((OPTIND - 1)))"; then
                OPTIND=$((OPTIND - 1))
            else
                 case $opt in
                     c) CHERRY="$OPTARG";;
                     d) DFRUIT="$OPTARG";;
                     ...
                esac
            fi ;;
        \?) ... ;;
        :)
             case "$OPTARG" in
                 c|d|e|f) ;; # Ignore missing arguments
                 *) echo "option requires an argument -- $OPTARG" >&2 ;;
            esac ;;
        esac
    done

This has worked for me so far.

0
Will Charlton On

For bash, this is my favorite way to parse/support cli args. I used getopts and it was too frustrating that it wouldn't support long options. I do like how it works otherwise - especially for built-in functionality.

usage()
{
    echo "usage: $0 -OPT1 <opt1_arg> -OPT2"
}
while [ "`echo $1 | cut -c1`" = "-" ]
do
    case "$1" in
        -OPT1)
                OPT1_ARGV=$2
                OPT1_BOOL=1
                shift 2
            ;;
        -OPT2)
                OPT2_BOOL=1
                shift 1
            ;;
        *)
                usage
                exit 1
            ;;
esac
done

Short, simple. An engineer's best friend!

I think this can be modified to support "--" options as well...

Cheers =)

0
bik On
#!/bin/bash

while getopts ":a:b:c:d:e:f:" opt; do
      case $opt in
        a ) APPLE="$OPTARG";;
        b ) BANANA="$OPTARG";;
        c ) CHERRY="$OPTARG";;
        d ) DFRUIT="$OPTARG";;
        e ) EGGPLANT="$OPTARG";;
        f ) FIG="$OPTARG";;
        \?) echo "Invalid option: -"$OPTARG"" >&2
            exit 1;;
        : ) echo "Option -"$OPTARG" requires an argument." >&2
            exit 1;;
      esac
    done
echo "Apple is "$APPLE""
echo "Banana is "$BANANA""
echo "Cherry is "$CHERRY""
echo "Dfruit is "$DFRUIT""
echo "Eggplant is "$EGGPLANT""
echo "Fig is "$FIG""