getopts in BASH

Using options with a BASH script is pretty annoying. I think the simplest route is to use getopts, which is a builtin BASH command. There are nicer ones, but then you need to install them. Here’s a bare-bones script (based on a script here):

# Arguments ending with colon take argument in $OPT_ARG
OPTSTR="ya:"

# Set a default for option A
OPT_A='out.txt'

while getopts "$OPTSTR" FLAG; do
#                       ^ put the option name in the variable "FLAG"
  case $FLAG in
    y)
        # do whatever, such as setting a variable
        CONFIRMED=true
        ;;
    a)
        ARG_A=$OPTARG
        ;;
  esac
done

# Get rid of all the optional arguments, we took care of them
shift $((OPTIND-1))

Then we can process our actual arguments. Here’s an example:

NUMARGS=$#
echo "Number of arguments: $NUMARGS"

if [ ! $NUMARGS -eq 1 ]; then
  echo "NOT ONE ARGUMENT"
  exit 1
fi

if [ -n "$CONFIRMED" ]; then
    echo "CONFIRMATION FOUND"
fi

echo "MAIN ARGUMENT: $1"

To do better error handling, we can add : to the beginning of the $OPTSTR, and then $FLAG will be \? for bad arguments:

OPTSTR=":y"

while getopts "$OPTSTR" FLAG; do
  case $FLAG in
    y)
        OPT_Y=1
        ;;
    \?)
        echo "Option $OPTARG not understood." #TODO: put a full help message in
        exit 2
        ;;
  esac
done