Parse short options with getopts
getopts optstring name [arg ...] is a Bash builtin for short options. A character followed by : in optstring requires a value; a leading : selects silent error mode. On each successful parse, the option is stored in name and its value, if any, in OPTARG. OPTIND tracks the next argument position; initialize it to 1 before parsing a new argument vector (use local OPTIND=1 in a function). After the loop, shift "$((OPTIND - 1))" leaves operands. Parsing normally stops at the first non-option or --. In silent mode, an unknown option yields ? and a missing required value yields :; OPTARG identifies the problematic option. These are cases inside the loop, not merely nonzero getopts statuses. OPTERR=0 suppresses built-in diagnostics even without silent mode, but does not change the result into silent-mode semantics. Required values may start with a dash; define and validate the value policy explicitly. For the demonstrated parser, repeated -n options use the last value; an explicitly empty value is accepted. A required argument may consume an option-looking token. This is a different contract from the stricter CLI Option Parser project.
Practical examples
Run each example as a separate script in a fresh noninteractive Bash 5.2 process and empty practice directory. Tests use C locale; do not enter expected output as code.
Parse short flags and values
parse() { local OPTIND=1 OPTARG opt verbose=0 name=guest while getopts ':vn:' opt; do case $opt in v) verbose=1 ;; n) name=$OPTARG ;; \?) printf 'unknown: %s\n' "$OPTARG" >&2; return 2 ;; :) printf 'missing: %s\n' "$OPTARG" >&2; return 2 ;; esac done shift "$((OPTIND - 1))" printf 'verbose=%s name=[%s] operands=%s\n' "$verbose" "$name" "$#"}parse -vn 'Ada Lovelace' -- file || exit 1parse -n first -n lastExpected stdout:
verbose=1 name=[Ada Lovelace] operands=1verbose=0 name=[last] operands=0The grouped flag is recognized, the operand survives, and local OPTIND allows repeated calls.
Inspect missing-value mode
set -- -nOPTIND=1getopts ':n:' optstatus=$?printf 'opt=%s arg=%s status=%s\n' "$opt" "$OPTARG" "$status"Expected stdout:
opt=: arg=n status=0An option was found, so getopts returns zero here despite the missing value. The caller must handle the colon.
Inspect an unknown option
set -- -xOPTIND=1getopts ':v' optprintf 'opt=%s arg=%s\n' "$opt" "$OPTARG"Expected stdout:
opt=? arg=xSilent mode supplies the offending option in OPTARG, with no automatic diagnostic.
Common mistakes
Do not assume getopts parses GNU-style long options. Do not forget to reset OPTIND on repeated calls or ignore the ? and : cases.
Practice
Build a parser for -v and -n NAME. Test -vn "Ada Lovelace", repeated -n, -x, -n with no value, and -- followed by an operand. Document whether the last repeated value wins.
Next: Long options and end-of-options