# getopts. parse() { OPTIND=1 while getopts ":ab:c" o "$@"; do case $o in a) echo "a" ;; b) echo "b=$OPTARG" ;; c) echo "c" ;; :) echo "missing arg for $OPTARG" ;; \?) echo "unknown $OPTARG" ;; esac done shift $((OPTIND - 1)) echo "rest: $*" } parse -a -b x y z parse -abval -c parse -ac -- -b parse -x -a parse -b parse - parse parse -b '' loud() { OPTIND=1 while getopts "ab:" o "$@"; do echo "o=$o OPTARG=${OPTARG-unset}"; done } loud -z 2>&1 | sed 's/^.*getopts/getopts/' loud -b 2>&1 | sed 's/^.*getopts/getopts/' set -- -a -b arg file while getopts ab: o; do echo "$o ${OPTARG-}"; done; echo "OPTIND=$OPTIND" getopts a o -q 2>/dev/null; echo "end status=$? o=$o"