getopts
Parse command-line options in shell scripts
TLDR
Check if an option is set
Set an option to require an argument and check said argument
Check for multiple options
Set getopts to silent mode and handle option errors
Reset getopts
SYNOPSIS
getopts optstring name [args...]
PARAMETERS
optstring
A string containing the option characters that getopts should recognize. If an option character is followed by a colon (:), the option requires an argument. If an option should be ignored put '+' symbol in front of the option character
name
The name of the shell variable to set with the option character found.
[args...]
Optional arguments to be parsed. If omitted, the positional parameters of the shell script are used.
DESCRIPTION
The getopts utility is a shell builtin used to parse command-line arguments. It's primarily designed for use within shell scripts to handle options passed to the script. getopts iterates through the arguments, extracting and setting shell variables based on the option strings provided. This allows a shell script to flexibly respond to different command-line flags and arguments. Unlike more sophisticated option parsing tools, getopts handles basic option parsing well, it only supports short options (single character options) and optional arguments and may require manual parsing of positional parameters following the options.
It is useful when scripting simple scripts which don't require too much of complexity in options provided
CAVEATS
getopts only handles short options (single characters). Long options (e.g., --verbose) are not supported directly. Positional arguments after the options must be handled separately. The parsing stops at the first non-option argument.
RETURN CODES
getopts returns 0 if an option was successfully parsed. It returns a non-zero value when it encounters the end of the options (indicated by '--') or an error. If an option requires an argument, and no argument is provided, getopts sets name to '?' and OPTARG to the name of the option.
SPECIAL VARIABLES
OPTIND: Automatically updated to the index of the next argument to be processed.
OPTARG: Set to the argument of an option that requires one.
EXAMPLE USAGE
```bash
while getopts "ab:c" opt;
do
case "$opt" in
a) echo "Option a";;
b) echo "Option b with argument $OPTARG";;
c) echo "Option c";;
\?) echo "Invalid option: -$OPTARG" >&2;;
:) echo "Option -$OPTARG requires an argument." >&2;;
esac
done
shift $((OPTIND-1))
# Remaining positional arguments are now in $*```
HISTORY
getopts has been a standard shell builtin for a long time, appearing in various Unix-like operating systems and standardized by POSIX. It predates more sophisticated command-line argument parsing libraries and tools found in languages like Python or Perl, serving as a basic but reliable way to handle options in shell scripts.
SEE ALSO
getopt(1), argparse(1)