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

NameTypeDescription
optstringstringRecognized option characters and colon markers.
namevariable nameReceives the parsed option or error marker.
argstringOptional 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
Bash Reference