builtin
getopts
Parse short options. A following colon requires a value; a leading colon selects silent mode. Returns 0 when an option is found, including silent error cases; nonzero at end of options or on invocation error. Reset OPTIND for a new vector.
Formal Syntax & Structure
bash syntaxbash
getopts optstring name [arg ...]Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| optstring | string | Recognized option characters and colon markers. |
| name | variable name | Receives the parsed option or error marker. |
| arg | string | Optional explicit argument vector. |
Return Value
exit status
Parse short options. A following colon requires a value; a leading colon selects silent mode. Returns 0 when an option is found, including silent error cases; nonzero at end of options or on invocation error. Reset OPTIND for a new vector.
Working Example
Example Snippetbash
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' -- fileparse -n first -n last