How can I handle command-line arguments (options) to my script easily?

Well, that depends a great deal on what you want to do with them. There are several approaches, each with its strengths and weaknesses.

Manual loop

This approach handles any arbitrary set of options, because you're writing the parser yourself. For 90% of programs, this turns out to be the simplest and most direct approach, since very few scripts need complicated option processing.

Here's an example that will handle a combination of short (-h) and long (--help) options.

# Bash
while [[ $1 == -* ]]; do
    case "$1" in
      -h|--help|-\?) show_help; exit 0;;
      -v|--verbose) verbose=1; shift;;
      -f) if (($# > 1)); then
            output_file=$2; shift 2
          else 
            echo "-f requires an argument" 1>&2
            exit 1
          fi ;;
      --) shift; break;;
      -*) echo "invalid option: $1" 1>&2; show_help; exit 1;;
    esac
done

Now all of the remaining arguments are the filenames which followed the optional switches. You can process those with for i or "$@".

A POSIX version of that same code:

# POSIX
while true; do
    case "$1" in
      -h|--help|-\?) show_help; exit 0;;
      -v|--verbose) verbose=1; shift;;
      -f) if [ $# -gt 1 ]; then
            output_file=$2; shift 2
          else 
            echo "-f requires an argument" 1>&2
            exit 1
          fi ;;
      --) shift; break;;
      -*) echo "invalid option: $1" 1>&2; show_help; exit 1;;
      *)  break;;
    esac
done

Some Bash programmers write this at the beginning of their scripts:

    set -u
    # or, set -o nounset

This way Bash stops if it's forced to work with the value of an unset variable. If you use set -o nounset, the Bash version of the "manual loop" shown above may break, if there are no additional non-option arguments. It can be fixed thus:

# Bash (with set -u)
while [[ ${1+defined} && $1 == -* ]]; do
    case "$1" in
      -h|--help|-\?) show_help; exit 0;;
      -v|--verbose) verbose=1; shift;;
      -f) if (($# > 1)); then
            output_file=$2; shift 2
          else 
            echo "-f requires an argument" 1>&2
            exit 1
          fi ;;
      --) shift; break;;
      -*) echo "invalid option: $1" 1>&2; show_help; exit 1;;
    esac
done

Of course, a simpler fix would be not to use set -u in the first place; or at least to use it only after the option processing is finished.

What these examples do not handle are:

It's certainly possible to do those things by changing the code, but at least in the first case, there's another approach that handles that automatically.

getopts

Never use getopt(1). getopt cannot handle empty arguments strings, or arguments with embedded whitespace. Please forget that it ever existed.

The POSIX shell (and others) offer getopts which is safe to use instead. Here is a simplistic getopts example:

# POSIX
OPTIND=1         # Reset in case getopts has been used previously in the shell.
while getopts "h?vf:" opt; do
  case "$opt" in
    h|\?) show_help; exit 0;;
    v) verbose=1;;
    f) output_file=$OPTARG;;
  esac
done
shift $((OPTIND-1))
if [ "$1" = -- ]; then shift; fi
echo "verbose=$verbose, output_file='$output_file', Leftovers: $@"

The disadvantage of getopts is that it can only handle short options (-h) without trickery. It handles -vf filename in the expected Unix way, automatically. getopts is a good candidate because it is portable and e.g. also works in dash.

There is a getopts tutorial which explains what all of the syntax and variables mean. In bash, there is also help getopts, which might be informative.

There is also still the disadvantage that options are coded in at least 2, probably 3 places - in the call to getopts, in the case statement that processes them and presumably in the help message that you are going to get around to writing one of these days. This is a classic opportunity for errors to creep in as the code is written and maintained - often not discovered till much, much later. This can be avoided by using callback functions, but this approach kind of defeats the purpose of using getopts at all.

Here is an example which claims to parse long options with getopts. The basic idea is quite simple: just put "-:" into the optstring. This trick requires a shell which permits the option-argument (i.e. the filename in "-f filename") to be concatenated to the option (as in "-ffilename"). The POSIX standard says there must be a space between them; bash and dash permit the "-ffilename" variant, but one should not rely on this leniency if attempting to write a portable script.

   1 #!/bin/bash
   2 # Uses bash extensions.  Not portable as written.
   3 optspec=":h-:"
   4 while getopts "$optspec" optchar; do
   5   case "${optchar}" in
   6     -)
   7       case "${OPTARG}" in
   8         loglevel)
   9           val="${!OPTIND}"; OPTIND=$(( $OPTIND + 1 ))
  10           echo "Parsing option: '--${OPTARG}', value: '${val}'" >&2;
  11           ;;
  12         loglevel=*)
  13           val=${OPTARG#*=}
  14           opt=${OPTARG%=$val}
  15           echo "Parsing option: '--${opt}', value: '${val}'" >&2
  16           ;;
  17       esac;;
  18     h)
  19       echo "usage: $0 [--loglevel[=]<value>]" >&2
  20       exit 2
  21       ;;
  22   esac
  23 done

Silly repeated brute-force scanning

Another approach is to check options with if statements "on demand". A function like this one may be useful:

# Bash
HaveOpt() {
  local needle=$1
  shift
  while [[ $1 == -* ]]; do
    case "$1" in
      --) return 1;; # by convention, -- is end of options
      $needle) return 0;;
    esac
    shift
  done
  return 1
}
if HaveOpt --quick "$@"; then echo "Option quick is set"; fi

and it will work if script is run as:

but will stop on first argument with no "-" in front (or on --):

Of course, this approach (iterating over the argument list every time you want to check for one) is far less efficient than just iterating once and setting flag variables.

It also spreads the options throughout the program. The literal option --quick may appear a hundred lines down inside the main body of the program, nowhere near any other option name. This is a nightmare for maintenance.

Complex nonstandard add-on utilities

bhepple suggests the use of process-getopt (GPL licensed) and offers this example code:

PROG=$(basename $0)
VERSION='1.2'
USAGE="A tiny example using process-getopt(1)"

# call process-getopt functions to define some options:
source process-getopt

SLOT=""
SLOT_func()   { [ "${1:-""}" ] && SLOT="yes"; }      # callback for SLOT option
add_opt SLOT "boolean option" s "" slot

TOKEN=""
TOKEN_func()  { [ "${1:-""}" ] && TOKEN="$2"; }      # callback for TOKEN option
add_opt TOKEN "this option takes a value" t n token number

add_std_opts     # define the standard options --help etc:

TEMP=$(call_getopt "$@") || exit 1
eval set -- "$TEMP" # just as with getopt(1)

# remove the options from the command line
process_opts "$@" || shift "$?"

echo "SLOT=$SLOT"
echo "TOKEN=$TOKEN"
echo "args=$@"

Here, all information about each option is defined in one place making for much easier authoring and maintenance. A lot of the dirty work is handled automatically and standards are obeyed as in getopt(1) - because it calls getopt for you.

It's written and tested on Linux where getopt(1) supports long options. For portability, it tests the local getopt(1) at runtime and if it finds an non-GNU one (ie one that does not return 4 for getopt --test) it only processes short options. It does not use the bash builtin getopts(1) command. -bhepple


CategoryShell