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
    The `optstring` defines valid options and whether they require an argument.
Characters in `optstring` represent valid options (e.g., `"ab:c"` means `-a`, `-b` with an argument, and `-c` are valid).
A colon `:` immediately following an option character indicates that it requires an argument.
A leading colon `:` in `optstring` enables "silent error reporting", preventing `getopts` from printing error messages for unknown options or missing arguments; instead, `OPTARG` and `name` are set specifically to indicate the error.

name
    The `name` of a shell variable that `getopts` will set to the current option character found (e.g., `'a'`, `'b'`, `'?'`, `':'`).

arg...
    Optional list of arguments to parse. If omitted, `getopts` parses the script's positional parameters (i.e., `$1`, `$2`, ...).

DESCRIPTION

getopts is a built-in shell command (commonly in Bash, ksh, zsh) used for parsing command-line options and arguments passed to shell scripts.
It provides a standardized and portable way to handle options following Unix conventions (e.g., -a, -b value).
The command iterates through the provided arguments, setting a specified variable (often `option_char`) to the current option character found.
If an option requires an argument, its value is placed in the `OPTARG` shell variable.
Additionally, `OPTIND` is a shell variable maintained by `getopts` that tracks the index of the next argument to be processed.
This mechanism simplifies the development of robust scripts that accept flexible command-line input, similar to standard utilities.

CAVEATS

getopts is a shell built-in, so its exact behavior may vary slightly between different shells (e.g., Bash, ksh, zsh).
It does not directly support long options like `--help`; for such cases, the external `getopt(1)` utility or manual parsing is generally required.
The `OPTIND` variable must be reset to 1 if `getopts` is intended to process a new set of arguments or if it's called multiple times within the same shell script instance to parse different argument lists.

SPECIAL VARIABLES

`getopts` interacts with and modifies specific shell variables during its execution:
OPTIND: The index of the next argument to be processed. It is initialized to 1 when a shell script starts or when the shell is invoked. It should be reset to 1 if `getopts` is called multiple times within the same script.
OPTARG: Contains the argument of the option found, if the option requires one. For example, if `-f filename` is parsed and `f:` is in `optstring`, then `OPTARG` will hold `filename`.
name (the variable passed to `getopts`): Stores the option character itself. If an invalid option is found, `'?'` is stored. If a required argument is missing (and `optstring` does not start with `:`), `'?'` is stored and an error message is printed. If `optstring` starts with `:` (silent error mode), `':'` is stored for a missing argument and `OPTARG` holds the option character (e.g., `'f'` for `-f`).

COMMON USAGE PATTERN

`getopts` is typically used within a `while` loop to process all options:
`while getopts optstring name; do
  case "$name" in
    a) echo "Option -a chosen";;
    b) echo "Option -b with argument $OPTARG";;
    \?) echo "Invalid option -$OPTARG"; exit 1;;
    :) echo "Option -$OPTARG requires an argument"; exit 1;;
  esac
done
`

After the loop, `shift $((OPTIND - 1))` is commonly used to remove the processed options and their arguments from the script's positional parameters, leaving only the non-option arguments (e.g., filenames) for further processing.

HISTORY

getopts was introduced as part of the POSIX standard to provide a consistent and portable way for shell scripts to parse command-line options.
It emerged as a simpler, more robust alternative to the older `getopt(1)` external utility for handling standard short options.
Its design focuses on efficiency and direct integration as a shell built-in, first appearing in shells like ksh and later adopted widely by Bash and zsh, establishing a common convention for script option parsing across Unix-like systems.

SEE ALSO

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

Copied to clipboard