Parsing Options with getopts
getopts is a Bash builtin that parses short options, the single-letter kind such as -v or -o FILE, according to the POSIX rules. Instead of writing a case pattern for every form an option can take (separate, attached, bundled), a script describes its options once in a short option string, and getopts hands them back one at a time. It handles bundled flags (-vn), attached values (-ofile), separate values (-o file), the -- marker and missing values automatically.
Because getopts is part of the POSIX shell standard, the same loop also works in other shells such as Dash. Its main limitation is that it understands only short options; long options like --verbose need the manual loop from lesson 127.
The Basic Loop
A getopts loop has three parts: the option string, a variable that receives each option letter, and a case statement that acts on it.
verbose=0 output=
while getopts "vo:" opt; do
case $opt in
v) verbose=1 ;;
o) output=$OPTARG ;;
?) echo "usage: g1.sh [-v] [-o FILE] [FILE...]" >&2; exit 2 ;;
esac
done
shift $((OPTIND - 1))
echo "verbose=$verbose output=[$output] OPTIND=$OPTIND"
echo "operands ($#):"; for a in "$@"; do echo " [$a]"; done
The Option String
"vo:" lists the options the script accepts:
vis a flag: an option without a value.o:has a colon after it, which means the option requires a value.
The order of the letters does not matter. Letters are case-sensitive, so "vV" declares two different options.
Each Call Returns One Option
Each time the while condition runs, getopts examines the arguments, finds the next option, and:
- stores the option letter in the named variable (
opthere); - stores the option's value, if it has one, in
OPTARG; - updates
OPTIND, the index of the next argument to examine; - returns status 0.
When there are no more options, getopts returns a non-zero status, which ends the while loop, and sets opt to ?.
Removing the Options with shift
After the loop, OPTIND is the position of the first argument that is not an option. shift $((OPTIND - 1)) removes everything before it (lesson 44), so "$@" contains only the operands. This line is almost always needed, and forgetting it leaves the options in "$@" mixed with the file names.
Running the Basic Loop
All the standard forms are accepted without any extra code:
$ bash g1.sh -v a.txt
verbose=1 output=[] OPTIND=2
operands (1):
[a.txt]
$ bash g1.sh -o out.txt a.txt b.txt
verbose=0 output=[out.txt] OPTIND=3
operands (2):
[a.txt]
[b.txt]
$ bash g1.sh -oout.txt a.txt
verbose=0 output=[out.txt] OPTIND=2
operands (1):
[a.txt]
$ bash g1.sh -vo out.txt a.txt
verbose=1 output=[out.txt] OPTIND=3
operands (1):
[a.txt]
In the last run, -vo is a bundle: getopts returned v, then o, and because o needs a value and nothing followed it inside the bundle, it took the next argument, out.txt.
The value of an option is whatever comes right after it, which can surprise users:
$ bash g1.sh -ov a.txt
verbose=0 output=[v] OPTIND=2
operands (1):
[a.txt]
Here v was the attached value of -o, not a flag. In the same way, -o -v a.txt sets output to -v, and -o "" a.txt sets it to an empty string. getopts never checks what a value looks like; validation (lesson 128) is still the script's job.
-- ends option parsing and is removed together with the options, so a file name that starts with a dash can be passed:
$ bash g1.sh -v -- -x.txt
verbose=1 output=[] OPTIND=3
operands (1):
[-x.txt]
A lone - is not an option, so it stays as an operand (bash g1.sh -v - a.txt gives the operands - and a.txt), and values with spaces survive as long as the user quotes them.
Watching getopts Work
Printing the variables inside the loop shows how OPTIND moves:
while getopts "vo:" opt; do
printf 'opt=%s OPTARG=[%s] OPTIND=%s\n' "$opt" "${OPTARG-}" "$OPTIND"
done
$ bash trace.sh -v -o out.txt -vo x a.txt
opt=v OPTARG=[] OPTIND=2
opt=o OPTARG=[out.txt] OPTIND=4
opt=v OPTARG=[] OPTIND=4
opt=o OPTARG=[x] OPTIND=6
After -v (argument 1), OPTIND is 2. After -o out.txt (arguments 2 and 3), it is 4. While getopts is still inside the bundle -vo, OPTIND stays at 4; it moves to 6 only when the bundle and its value x are used up. Argument 6, a.txt, is the first operand. After the loop, opt holds ?.
Options Stop at the First Operand
getopts follows the POSIX rule: parsing stops at the first argument that is not an option. Options placed after a file name are not recognized:
$ bash g1.sh a.txt -v
verbose=0 output=[] OPTIND=1
operands (2):
[a.txt]
[-v]
-v became an operand. This is how traditional Unix tools behave, but it differs from most GNU tools, which accept options anywhere. Scripts that use getopts should document that options come first. If accepting options after operands matters, the manual loop from lesson 127 is the better tool.
Error Handling: Normal Mode
When getopts finds an option that is not in the option string, or an option that is missing its required value, it reports the problem itself and sets the variable to ?:
$ bash g1.sh -x a.txt
g1.sh: illegal option -- x
usage: g1.sh [-v] [-o FILE] [FILE...]
$ bash g1.sh -o
g1.sh: option requires an argument -- o
usage: g1.sh [-v] [-o FILE] [FILE...]
The first line of each comes from getopts, the usage line from the script's ?) branch, which then exits with status 2. Long options are not understood at all; --verbose is seen as the option letter - followed by more letters:
$ bash g1.sh --verbose
g1.sh: illegal option -- -
In a case statement, ? is a pattern that matches any single character. It works as the last branch in this example because the real options were matched first, but writing it as \? (or '?') matches only a literal question mark and is clearer.
Setting the variable OPTERR to 0 turns off the built-in messages, but then the script cannot tell which option was wrong: for both problems above, opt is ? and OPTARG is unset. Silent mode, below, is the better solution.
Error Handling: Silent Mode
A colon at the start of the option string switches getopts into silent mode. It prints nothing and gives the script the details instead:
- for an unknown option, the variable is set to
?andOPTARGholds the unknown letter; - for a missing value, the variable is set to
:andOPTARGholds the option letter that needed the value.
prog=${0##*/}
while getopts ":vo:" opt; do
case $opt in
v) echo "got -v" ;;
o) echo "got -o with [$OPTARG]" ;;
:) printf "%s: option '-%s' requires an argument\n" "$prog" "$OPTARG" >&2; exit 2 ;;
\?) printf "%s: unknown option '-%s'\n" "$prog" "$OPTARG" >&2; exit 2 ;;
esac
done
$ bash g2.sh -x
g2.sh: unknown option '-x'
$ bash g2.sh -o
g2.sh: option '-o' requires an argument
$ bash g2.sh -vx
got -v
g2.sh: unknown option '-x'
Each error run ended with status 2. Silent mode lets the messages follow the script's own format (lesson 125), which is why most scripts use it. The order of options in the loop matters: in the last run, -v was processed before -x was found, so the script had already acted on -v before it exited. This is one more reason to keep the parsing loop free of real work and only set variables in it.
getopts in Functions: Resetting OPTIND
OPTIND starts at 1 when the shell starts, and getopts does not reset it. A function that calls getopts a second time therefore starts where the previous call stopped:
parse_flags() {
while getopts "ab" opt; do echo " flag -$opt"; done
shift $((OPTIND - 1))
echo " rest: $*"
}
echo "first call:"; parse_flags -a -b x
echo "second call:"; parse_flags -a y
first call:
flag -a
flag -b
rest: x
second call:
rest:
The second call found no options, because OPTIND was still 3 from the first call, and the shift then removed both arguments. Declaring local OPTIND opt at the start of the function (lesson 92) gives each call a fresh OPTIND, and the second call then prints flag -a and rest: y. Setting OPTIND=1 before the loop works too.
Parsing a Different List
By default, getopts reads the positional parameters. Extra arguments after the variable name make it parse that list instead, leaving the script's own arguments untouched:
set -- -q -n 3 file
while getopts "n:q" opt -x -n 5 other; do
printf 'opt=%s OPTARG=%s\n' "$opt" "${OPTARG-}"
done
echo "positional still: $*"
g6.sh: illegal option -- x
opt=? OPTARG=
opt=n OPTARG=5
positional still: -q -n 3 file
This is mainly useful inside functions that parse an array, as in getopts "n:q" opt "${args[@]}".
Portability
getopts is specified by POSIX, so the same loop runs in Dash and other POSIX shells. Running the first example with Dash gave the same results for the valid inputs tested (-vo out.txt a.txt, -o out.txt a.txt b.txt, a.txt -v and -v -- -x.txt); only the built-in error message differed (Illegal option -x). The [[ ]] tests and arrays used elsewhere in this tutorial are Bash features, so a script needs only getopts itself to be portable if it avoids those too (lesson 188).
getopts is different from the external command getopt (without the s). The util-linux version of getopt on Linux supports long options, but it is a separate program with its own syntax, and versions on other systems behave differently. This tutorial uses the builtin.
A Complete Example
rotate.sh rotates log files: app.log.1 becomes app.log.2 and so on, app.log becomes app.log.1, and a new empty app.log is created. It accepts a value option (-k), three flags (-z, -n, -v) and help (-h), all parsed with getopts in silent mode.
#!/usr/bin/env bash
# rotate.sh [-k KEEP] [-z] [-n] [-v] [-h] FILE...: rotate log files
set -euo pipefail
prog=${0##*/}
usage() {
cat <<USAGE
usage: $prog [-k KEEP] [-z] [-n] [-v] [-h] FILE...
Rotate each FILE: FILE.1 becomes FILE.2 and so on, FILE becomes FILE.1,
and a new empty FILE is created. Copies older than KEEP are removed.
-k KEEP number of old copies to keep, 1-99 (default: 5)
-z compress rotated copies with gzip
-n dry run: show what would be done, change nothing
-v print each action
-h show this help
USAGE
}
bad_usage() {
printf '%s: %s\n' "$prog" "$*" >&2
printf "Try '%s -h' for more information.\n" "$prog" >&2
exit 2
}
keep=5 compress=0 dry_run=0 verbose=0
while getopts ":k:znvh" opt; do
case $opt in
k) keep=$OPTARG ;;
z) compress=1 ;;
n) dry_run=1 ;;
v) verbose=1 ;;
h) usage; exit 0 ;;
:) bad_usage "option '-$OPTARG' requires an argument" ;;
\?) bad_usage "unknown option '-$OPTARG'" ;;
esac
done
shift $((OPTIND - 1))
[[ $keep =~ ^[0-9]{1,2}$ ]] && (( 10#$keep >= 1 )) \
|| bad_usage "KEEP must be a number from 1 to 99, got '$keep'"
keep=$((10#$keep))
(( $# > 0 )) || bad_usage "no log file given"
run() { # run COMMAND...: show and/or execute one action
if (( dry_run )); then
printf 'would run:%s\n' "$(printf ' %q' "$@")"
return 0
fi
(( verbose )) && printf 'run:%s\n' "$(printf ' %q' "$@")"
"$@"
}
rotate_one() {
local log=$1 ext= i
(( compress )) && ext=.gz
[[ -f $log ]] || { printf '%s: %s: not a regular file\n' "$prog" "$log" >&2; return 1; }
# set -e does not apply here (the caller uses ||), so every step checks itself
# drop the oldest copy, then move the others up by one
if [[ -e $log.$keep$ext ]]; then run rm -f -- "$log.$keep$ext" || return; fi
for (( i = keep - 1; i >= 1; i-- )); do
if [[ -e $log.$i$ext ]]; then run mv -- "$log.$i$ext" "$log.$((i + 1))$ext" || return; fi
done
run mv -- "$log" "$log.1" || return
run touch -- "$log" || return
if (( compress )); then run gzip -- "$log.1" || return; fi
}
status=0
for log in "$@"; do
rotate_one "$log" || status=1
done
exit "$status"
How It Works
":k:znvh": the leading colon selects silent mode,k:takes a value, the other letters are flags.- The loop only records choices. The
:and\?branches turngetopts' findings into the script's own usage messages and exit with status 2. - Validation follows the loop.
-kmust be 1 to 99;10#accepts input such as08(lesson 128). At least one file is required. runprints each command withprintf %q(so names with spaces are visible) when-nor-vis given, and executes it unless-nwas given. Implementing dry run in one function means no action can forget to respect it.rotate_onemoves copies from the highest number down, so no file is overwritten before it has been moved. When rotation would create one copy too many, the oldest copy is removed first.|| returnafter each step is needed because the function is called asrotate_one "$log" || status=1, andset -eis ignored inside a function called on the left of||(lesson 119). Each failure ends the function with the failing command's status.
Running the Complete Example
The folder holds app.log (today), app.log.1 (old1), app.log.2 (old2) and web server.log.
A dry run with two copies to keep shows the plan and changes nothing:
$ bash rotate.sh -n -k 2 app.log
would run: rm -f -- app.log.2
would run: mv -- app.log.1 app.log.2
would run: mv -- app.log app.log.1
would run: touch -- app.log
The same with -v instead of -n performs the actions:
$ bash rotate.sh -v -k 2 app.log
run: rm -f -- app.log.2
run: mv -- app.log.1 app.log.2
run: mv -- app.log app.log.1
run: touch -- app.log
Afterwards app.log is empty, app.log.1 contains today and app.log.2 contains old1; the old old2 copy is gone.
Bundled flags with compression, on a name that contains a space:
$ bash rotate.sh -vz "web server.log"
run: mv -- web\ server.log web\ server.log.1
run: touch -- web\ server.log
run: gzip -- web\ server.log.1
The folder now holds web server.log.1.gz. A second run with -z moved it to web server.log.2.gz and compressed the new copy; zcat showed that the .2.gz file still held the original content.
Usage errors end with status 2 and change nothing:
$ bash rotate.sh -k 0 app.log
rotate.sh: KEEP must be a number from 1 to 99, got '0'
Try 'rotate.sh -h' for more information.
$ bash rotate.sh -k
rotate.sh: option '-k' requires an argument
Try 'rotate.sh -h' for more information.
$ bash rotate.sh -q app.log
rotate.sh: unknown option '-q'
Try 'rotate.sh -h' for more information.
$ bash rotate.sh
rotate.sh: no log file given
Try 'rotate.sh -h' for more information.
A file problem affects only that file:
$ bash rotate.sh app.log missing.log
rotate.sh: missing.log: not a regular file
The status was 1, and app.log was rotated anyway.
Finally, the POSIX parsing rule in action. Because parsing stops at the first operand, -v placed after the file name is treated as a second file:
$ bash rotate.sh app.log -v
rotate.sh: -v: not a regular file
app.log was rotated without verbose output, and the script ended with status 1. The help text could state this rule explicitly, for example with a line such as "Options must come before FILE", which is one of the topics of lesson 131.