Bash 5 reference · Shell Builtins and Syntax
getopts (Bash builtin)
Parse short command-line options such as -v and -o FILE in scripts, with errors for unknown options.
Bash 5
Syntax
while getopts ":vo:" opt; do case $opt in ...; esac; done; shift $((OPTIND - 1))
Parameters
| Parameter | Description |
|---|---|
":vo:" |
Leading : for silent errors; o: takes an argument. |
$OPTARG |
The option's argument. |
$OPTIND |
Index of the next argument. |
Examples
parse() {
local OPTIND opt verbose=0 out=-
while getopts ':vo:' opt; do
case $opt in v) verbose=1 ;; o) out=$OPTARG ;; *) echo "bad option -$OPTARG"; return 2 ;; esac
done
shift $((OPTIND - 1))
echo "verbose=$verbose out=$out rest=$*"
}
parse -v -o report.txt a b
parse -x || echo "status $?"
Output
verbose=1 out=report.txt rest=a b bad option -x status 2
Run this on your computer — see “Get Started” for setup.
opts() {
local OPTIND opt
while getopts ':n:' opt; do
case $opt in
n) echo "name=$OPTARG" ;;
:) echo "-$OPTARG needs a value"; return 2 ;;
esac
done
}
opts -n api
opts -n || echo "status $?"
Output
name=api -n needs a value status 2
Run this on your computer — see “Get Started” for setup.
Related
function· Group commands into a named function that takes arguments like a script ($1, $@) and returns an exit status.- Bash Script Arguments and Options · tutorial