commands

getopts — parse short options

Bash builtin parses short options; OPTARG receives values and OPTIND tracks the next argument. Reset OPTIND for independent parses. A leading colon enables quiet error handling. Example assumes a fresh shell lab fixture with new output names.

Formal Syntax & Structure

linux syntaxlinux
getopts OPTSTRING NAME [ARG...]

Parameters & Attributes

NameTypeDescription
OPTSTRINGoperandoption specification
NAMEoperandvariable receiving option
ARGoperandoptional argument list

Return Value

exit status and output

Bash builtin parses short options; OPTARG receives values and OPTIND tracks the next argument. Reset OPTIND for independent parses. A leading colon enables quiet error handling.

Working Example

Example Snippetlinux
set -- -o previewOPTIND=1while getopts ':o:' opt; do printf '%s=%s\n' "$opt" "$OPTARG"; done
Linux Reference