A backup script built for this post accepted -o dir to pick an output folder. Called as ./backup.sh -o -v e.txt, it set the output folder to -v. No error, no warning. Called as ./backup.sh a.txt -v, it treated -v as a second filename. Both are correct behavior for getopts, the shell’s built-in option parser, and both are worth knowing before shipping a script anyone else will run. Everything below was tested in GNU Bash 5.2.21, with a few comparisons in dash.
What getopts does
A standard, built in
getopts is part of POSIX, not a Bash extra. The POSIX specification opens with one line: “The getopts utility shall retrieve options and option-arguments from a list of parameters.” It handles short, single-letter options like -v and -o dir, combined flags like -vn, and the -- marker that ends option parsing. The same loop ran unchanged under dash on the test machine.
The syntax
The Bash manual’s builtins page gives it as getopts optstring name [arg ...]. Each call reads the next option, puts the letter in the variable name, and returns true. When the options run out, “It returns false when it encounters the end of options or if an error occurs,” which is what ends the while loop.
The option string
The option string lists every valid letter. The manual’s rule: “if a character is followed by a colon, the option is expected to have an argument.” So "vno:h" means -v, -n and -h are plain flags, and -o takes a value, which arrives in the variable OPTARG.

A complete script
The template
#!/usr/bin/env bash
usage() { echo "usage: $0 [-v] [-n] [-o dir] file..." >&2; exit 2; }
verbose=0 dry=0 out=/tmp
while getopts ":vno:h" opt; do
case $opt in
v) verbose=1 ;;
n) dry=1 ;;
o) out=$OPTARG ;;
h) usage ;;
:) echo "option -$OPTARG needs an argument" >&2; usage ;;
\?) echo "unknown option -$OPTARG" >&2; usage ;;
esac
done
shift $((OPTIND - 1))
[ $# -gt 0 ] || usage
echo "verbose=$verbose dry=$dry out=$out files=[$*] count=$#"What it accepted
| Arguments | Result |
|---|---|
-v a.txt |
verbose=1, files=[a.txt] |
-vn -o /srv b.txt c.txt |
verbose=1, dry=1, out=/srv, 2 files |
-o/srv d.txt |
out=/srv, files=[d.txt] |
-n -- -weird.txt |
dry=1, files=[-weird.txt] |
Combined flags -vn split correctly. -o/srv with no space worked too; POSIX says getopts “shall interpret the characters following an option character requiring arguments as an argument” whether or not they’re separated. And -- let a filename that starts with a dash through as a file instead of an option.
Why shift $((OPTIND - 1))
OPTIND holds the position of the next argument to read. When the loop finishes, everything before OPTIND was an option. Shifting them away leaves $@ holding only the file names, so the rest of the script can treat $1, $# and "$@" as the real inputs.
Errors, loud and silent
The leading colon
The option string above starts with a colon: ":vno:h". That switches getopts into silent mode. Per the manual, on an unknown option silent mode “assigns the option character found to OPTARG and does not print a diagnostic message,” setting the variable to ?. On a missing argument it sets the variable to : instead. The script then prints its own messages:
-x a.txt => unknown option -x
-o => option -o needs an argument
Both exited with status 2 after the usage line.
Without the colon
Normal mode prints its own error and gives less to work with:
bash -c 'while getopts "vo:" opt; do echo "opt=$opt OPTARG=${OPTARG-unset}"; done' x -x -ox: illegal option -- x
opt=? OPTARG=unset
x: option requires an argument -- o
opt=? OPTARG=unset
Both errors produce the same ? with OPTARG unset, so the script can’t tell an unknown option from a missing value. The manual confirms both: in normal mode getopts “prints an error message and unsets OPTARG.” Silent mode is the better default for scripts that want clear messages.

The two quiet traps
An option that swallows the next option
./backup.sh -o -v e.txt returned out=-v. Since -o takes an argument, getopts took the next word as that argument, whatever it looked like. POSIX expects an option-argument “as a separate argument,” and -v is a separate argument. A script that cares can check: [[ $OPTARG == -* ]] && { echo "-o needs a directory"; usage; } inside the o) branch.
Options after the first file are ignored
./backup.sh a.txt -v produced files=[a.txt -v] count=2. getopts stops at the first argument that isn’t an option, so everything after a.txt was treated as a file name. That’s standard POSIX behavior, and it differs from many GNU tools, which let options appear anywhere. Users used to ls file -l will be surprised. The usage line should show options first, and the README should say so.
Long options aren’t supported
Passing --verbose printed unknown option -. getopts saw --verbose as the dash option -, followed by letters, and had no - in its option string. The POSIX page mentions -- only as the end-of-options marker; it has no concept of long options. Scripts that want --verbose style flags either handle them in a case before calling getopts or use the external getopt program from util-linux, which is a different tool with a similar name.
OPTIND and functions
The reset problem
The manual warns that OPTIND “is initialized to 1 each time the shell or a shell script is invoked,” and that “it must be manually reset between multiple calls to getopts within the same shell invocation.” A test with two functions showed exactly what goes wrong:
f(){ local OPTIND opt; while getopts "a" opt; do echo "f got -$opt"; done; }
g(){ while getopts "a" opt; do echo "g got -$opt"; done; }
f -a; f -a; g -a; g -af got -a
f got -a
g got -a
f, which declares OPTIND local, parsed its option both times. g, which doesn’t, parsed it once. The second call to g started from OPTIND=2, found nothing past the end, and silently did nothing. Any function that uses getopts should start with local OPTIND.

When to use something else
getopts strengths
It’s built in, portable across POSIX shells, needs no dependencies and handles the common cases correctly: combined flags, attached or separate arguments, --, and clear error branches in silent mode. For a script with a handful of single-letter options, it’s the right tool.
Its limits
No long options, no options after operands and no optional arguments. Scripts that need GNU-style interfaces with --long-name=value either parse by hand with a while and case over "$@", or use util-linux getopt and accept that it isn’t on every system, macOS included. Past a certain point, a script with a dozen options is a sign it may be time to rewrite it in a language with a real argument parser.
A hand-rolled parser for long options
When long options are a must, a plain while loop over the arguments handles them without any external tool:
verbose=0 out=/tmp files=()
while (( $# )); do
case $1 in
-v|--verbose) verbose=1 ;;
-o|--out) [[ $# -ge 2 && $2 != -* ]] || { echo "$1 needs a directory" >&2; exit 2; }
out=$2; shift ;;
--out=*) out=${1#--out=} ;;
--) shift; files+=("$@"); break ;;
-*) echo "unknown option $1" >&2; exit 2 ;;
*) files+=("$1") ;;
esac
shift
doneTested against the same kinds of input:
| Arguments | Result |
|---|---|
--verbose a.txt |
verbose=1, 1 file |
a.txt --out=/srv b.txt |
out=/srv, 2 files |
--out /srv -v c.txt |
verbose=1, out=/srv, 1 file |
-o -v e.txt |
“-o needs a directory”, exit 2 |
-- -x.txt |
1 file, -x.txt |
--bogus |
“unknown option –bogus”, exit 2 |
It fixes both quiet traps from earlier: options can follow file names, and -o -v is caught. The cost is that combined flags like -vn no longer work unless the loop splits them itself.
util-linux getopt
The external getopt on the test machine reported getopt from util-linux 2.39.3. Given -o vo: -l verbose,out: and the arguments --verbose a.txt --out /srv b.txt, it printed a reordered, quoted list: --verbose --out '/srv' -- 'a.txt' 'b.txt'. Options move to the front and files go after --, ready for a simple loop like the one above to consume with eval set --.
A checklist for the template
- Start the option string with
:and handle:and\?cases. shift $((OPTIND - 1))after the loop.local OPTINDinside functions.- Check for missing operands after the shift.
- Print usage to standard error and exit with a non-zero status, 2 by common convention for usage errors.
Sources
- The Open Group, POSIX, “getopts”: https://pubs.opengroup.org/onlinepubs/9799919799/utilities/getopts.html
- GNU Bash Reference Manual, “Bourne Shell Builtins”: https://www.gnu.org/software/bash/manual/html_node/Bourne-Shell-Builtins.html
