Reading $OPTARG for optional flags? Reading $OPTARG for optional flags? bash bash

Reading $OPTARG for optional flags?


: 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.


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.


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            ;;esacdone

Short, simple. An engineer's best friend!

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

Cheers =)