Table of Contents

Handling Command Line Options (getopts)

Most Unix command line utilities we have looked at provide multiple command line options. Some of them, such as tar allow you to flexibly combine command line options to modify command behavior in multiple ways at once.

The shell (bash) provides the getopts construct that allows you to add flexible command line option handling to shell scripts.

The getopts construct

Sample script #1 that uses getopts:

#!/bin/bash

# getopts_test1
# This script has 3 command line options, one of which takes an argument.

function usage {
      echo "script usage: $(basename $0) [-l] [-m] [-o somevalue]" >&2
      exit 1
}

while getopts 'lmo:' OPTION; do
  case "$OPTION" in
    l)
      echo "option l selected"
      ;;

    m)
      echo "option m selected"
      ;;

    o)
      oarg="$OPTARG"
      echo "The o option's argument was $oarg"
      ;;
    ?)
      usage
      ;;
  esac
done

shift "$(($OPTIND - 1))"
./getopts_test1 -l -m
./getopts_test1 -l -m -o 3
./getopts_test1 -lm
./getopts_test1 -lm -o 3
./getopts_test1 -lmo 3
./getopts_test1 -lmo3
./getopts_test1 -o 3 -l -m
./getopts_test1 -o3 -lm
./getopts_test1 -o3 -m
(and more)
./getopts_test1 -o 3 -l -m  # $OPTIND = 4
./getopts_test1 -o3 -lm     # $OPTIND = 4
./getopts_test1 -l -m       # $OPTIND = 2
./getopts_test1 -lm         # $OPTIND = 2

Command line options plus additional arguments

Sample script #2 that uses getopts:

#!/bin/bash

# getopts_test2:
# This script has 3 command line options and
# takes an additional script argument ($1)

while getopts dmy OPTION
do
        case $OPTION in
          d) dopt=1;;
          m) mopt=1;;
          y) yopt=1;;
          ?) echo "Unrecognized or invalid option"
             exit 1;;
        esac
done

if [ ! -z $dopt ]; then
    day=$(date '+%d')
fi

if [ ! -z $mopt ]; then
    mon=$(date '+%b')
fi

if [ ! -z $yopt ]; then
    year=$(date '+%Y')
fi

shift $(($OPTIND - 1))

echo "The date is: $day $mon $year"

if [ ! -z $1 ]; then
   echo "Welcome, $1."
fi
./getopts_test2 -d -m -y Dave
./getopts_test2 -dmy Dave

Example: text2png_getopts

Test a version of the text2png script that uses getopts for command line options handling: text2png_getopts