getopts
The builtin that parses short command-line options such as -v, -vq and -f value, one option per call, in a while loop.
In more detail
Each call sets a variable to the option letter and OPTARG to its value, and a case statement acts on it. getopts handles bundled flags and values for you, but only single-letter options, not long ones such as --verbose.
Example
while getopts ":vf:" opt; do case "$opt" in v) verbose=1 ;; f) file="$OPTARG" ;; esac; doneRelated terms
- option string — The string given to getopts listing the option letters a script accepts, with a colon after each letter that takes a value.
- OPTARG — The variable getopts fills with the value of an option that takes one, such as the file name after -f.
- OPTIND — The variable getopts uses to track which argument it will read next; after the loop it points at the first operand.
- case statement — A statement that compares one value against several glob patterns and runs the block for the first that matches.
Taught in
- Arguments: Dollar One, Dollar At, shift — Bash Scripting & Command Line Automation
- Option Parsing With getopts — Bash Scripting & Command Line Automation
- trap, Cleanup And Temporary Files — Bash Scripting & Command Line Automation
- Scheduling, Monitoring And A Script That Reports — Bash Scripting & Command Line Automation