shell programming - options parsing

created onJanuary 18, 2022

There are several methods for the parsing options / parameters supplied to the shell script .

space-separated

while [[ $# -gt 0 ]]; do key="$1" shift case $key in -w|--what) what="$1" shift ;; -e|--ever) ever="$1" shift # past value ;; -s|--simplified) simplified=true # note we don't shift here ;; *) # everything else printf "munching $1, doesn't apply here" # same as above, no shift here ;; esac done

equals-separated

while [[ $# -gt 0 ]]; do key="$1" shift case $key in -w=*|--what=*) what="${i#*=}" shift ;; -e=*|--ever=*) ever="${i#*=}" shift # past value ;; -s|--simplified) simplified=true # note we don't shift here ;; *) # everything else printf "munching $1, doesn't apply here" # same as above, no shift here ;; esac done

getopts

# POSIX variable OPTIND=1 # reset getopts (might have used before in the shell) while getopts "wes:" key; do case "$key" in w) what=$OPTARG ;; e) ever=$OPTARG ;; f) simplified="true" ;; esac done shift $((OPTIND-1))

getopt

  • you need to call getopts several times. each time it will use the next positional parameter and a possible argument, if parsable, and provide it.
  • getopts sets an exit status of FALSE when there’s nothing left to parse
  • getopts will parse options and their possible arguments. will stop parsing on the first non-option argument (a string that doesn’t begin with a hyphen (-) that isn’t an argument for any option in front of it). also stops parsing when encountering – (double-hyphen, which means end of options).
  • more portable, works in other shells like dash.
  • can handle multiple single options like -we whatever in the typical Unix way.
  • can only handle short options

getopt manual: https://wiki.bash-hackers.org/howto/getopts_tutorial

getopt vs getopts

getopt getopts
standards none POSIX, Unix, Linux LSB
long options yes no
optional args ? no