getopts Bash builtin

I did not find the output from man builtins all that useful in learning how to use getopts. Fortunately, the Bash Hackers Wiki clicked right away.
getopts_demo() {
local loop=0 OPTERR=0 optstring=":ab:c:de:"

  echo "# processing getopts ${optstring} on '${@}'"

  while getopts ${optstring} OPT; do
    msg=""
    case ${OPT} in
      \?    )
        msg="failure -${OPTARG} is invalid"; OPTERR=$[${OPTERR}+1];;
      :     )
        msg="failure -${OPTARG} requires a value." OPTERR=$[${OPTERR}+1];;
      a|d   ) msg="success -${OPT} -> ${OPT}flag=1";;
      b|c|e ) msg="success -${OPT}=${OPTARG}";;
    esac
    loop=$[${loop}+1]
    cat << EOF
  # loop=${loop}
    OPTIND=${OPTIND:-} OPT=${OPT}
    OPTARG=${OPTARG:-''} OPTERR=${OPTERR:-}
    msg=${msg}
EOF
  done
  return ${OPTERR}
}

set -o nounset
getopts_demo -a -b world -e -f -g -c
echo "# ?=${?}"
The code above defines and calls a function named getopts_demo. Here’s the output:
# processing getopts :ab:c:de: on '-a -b world -e -f -g -c'
  # loop=1
    OPTIND=2 OPT=a
    OPTARG='' OPTERR=0
    msg=success -a -> aflag=1
  # loop=2
    OPTIND=4 OPT=b
    OPTARG=world OPTERR=0
    msg=success -b=world
  # loop=3
    OPTIND=6 OPT=e
    OPTARG=-f OPTERR=0
    msg=success -e=-f
  # loop=4
    OPTIND=7 OPT=?
    OPTARG=g OPTERR=1
    msg=failure -g is invalid
  # loop=5
    OPTIND=8 OPT=:
    OPTARG=c OPTERR=2
    msg=failure -c requires a value.
# ?=2
Make sure to note that loop 3 has an error that goes undetected. It makes no sense that -e=-f. Let me know if you have any questions.

About this entry