LinuxCommandLibrary

getopts

Parse command-line options in shell scripts

TLDR

Check if an option is the first set option in the current context

$ getopts [x] [opt]; echo $[opt]
copy

Check if an option is set in a string (specified option must be the first element of the string)
$ getopts [x] [opt] "[string text]"; echo $[opt]
copy

Set an option to require an argument and print them
$ getopts [x]: [opt]; echo $[opt] $OPTARG
copy

Check for multiple options
$ while getopts [xyz] [opt]; do case $[opt] in x) [echo x is set];; y) [echo y is set];; z) [echo z is set];; esac; done
copy

Set getopts to silent mode and handle option errors
$ while getopts :[x:] [opt]; do case $[opt] in x) ;; :) [echo "Argument required"];; ?) [echo "Invalid argument"] esac;; done
copy

Reset getopts
$ OPTIND=1
copy

SYNOPSIS

getopts optstring name [arg ...]

PARAMETERS

optstring
    Defines valid options: letters for flags, : after a letter for required arg (e.g., ab:c). Leading : suppresses error output.

name
    Shell variable name to assign option letter (or ? on error).

[arg ...]
    Arguments to parse; defaults to $1 $2 ... if omitted.

DESCRIPTION

getopts is a builtin command in POSIX-compliant shells (e.g., bash, sh) for reliably parsing short command-line options in scripts. It handles options like -a, bundled -abc, and those with arguments -c value or -cvalue, stopping at non-options or --. Typical usage in a loop:
while getopts "ab:c" opt; do
  case $opt in
    a) echo "Option a";;
    b) echo "Option b";;
    c) echo "Option c arg: $OPTARG";;
    ?) exit 1;;
  esac
done


It sets variable name (opt above) to the option letter or ? for invalid. OPTARG holds the argument if required; OPTIND tracks the next argument index (starts at 1, increments automatically). After options, remaining args start at ${@:$OPTIND}. This automates parsing per POSIX standards, avoiding fragile shift loops or case on $1. Portable across Unix systems, but limited to short options.

CAVEATS

Supports only short single-char options (-a); no long options (--foo). Stops at first non-option unless POSIXLY_CORRECT=1. Not reentrant; resets OPTIND externally.

SPECIAL VARIABLES

OPTIND: Next arg index to process (set to 1 before loop).
OPTARG: Value of option argument.
name=?: Unknown option or missing arg (unless optstring starts with :).

OPTSTRING EXTENSIONS

: after letter: requires arg.
Leading :: no stderr on errors.
+ prefix (non-POSIX): stop at first non-option.

HISTORY

Specified in POSIX.1-2001 (with earlier roots in SVR4 Unix and Korn shell). Standardized for portable shell scripting; bash/ksh/zsh implement as builtin since 1980s.

SEE ALSO

getopt(1), bash(1), sh(1)

Copied to clipboard