Bash getopts example

· 200 words · 1 minute read

This is a small example how to use getopts in bash. I wrote it down for my own sake, as my own cheatsheet :)

#!/bin/bash

# Print help on stderr
function show_help(){
    show_usage
    cat >&2 <<EOF

Explain all about $(basename $0) here.
EOF
}

# Print usage on stderr
function show_usage() {
    echo "$(basename $0) [-a ARG] [-b] [N1 [N2 .. [NN]]]" >&2
}

# Print usage and exit with error code 1 if we don't have any options
if [[ "$@" = "" ]]; then
    show_usage
    exit 1
fi

# :  = make getopts silent, handle errors self
# a: = option a expects an argument
# b  = option b is a true false option
# h  = option h is a true false option
#
# On invalid option, opt will be replaced with ?
# and OPTARG set to argument name
while getopts ":a:bh" opt
do
    case $opt in
        a)  echo $OPTARG;;
        b)  echo True;;
        h)  show_help; exit 1;;
        \?) echo $(basename $0) invalid option: -$OPTARG >&2
            exit 1
            ;;
    esac
done

# OPTIND is not reset after getopts is finished.
# Loop through argument  [N1 [N2 .. [NN]]]
for ARG in ${@:$OPTIND}
do
    echo $ARG
done