Parsing options with getopts
Give a script real command-line options with getopts: flags, options with values, error handling, OPTIND and shift, and where getopts stops.
Case statementsFunctions, arguments and scopeExit status and && / || lists
Parsing options with getopts
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- `getopts ':hqs:n:' opt` parses one option per call and is used in a `while` loop. A letter followed by a colon takes a value, which arrives in `$OPTARG`.
- A leading colon in the option string turns on silent mode, so the script prints its own errors. Bad options set `opt` to `?` and missing values set it to `:`.
- After the loop, `shift $((OPTIND - 1))` removes the parsed options and leaves the remaining arguments in `$@`.
- `getopts` stops at the first non-option argument, so `cmd file -q` treats `-q` as a file. Options must come first.
- `getopts` is a builtin that handles short options only. It has no long options like `--help`, and the external `getopt` command differs between macOS and Linux.
From positional arguments to options
Positional arguments work until a script grows features. Is logsum 5 the status class or a file? Which order do they go in? Real commands solve this with options: -q, -s 5, -n 10. Parsing those by hand with a case on $1 and a lot of shifts is possible and tedious, and it gets combined flags like -qs 4 wrong.
Bash ships a builtin for it: getopts. Each call takes the next option from the argument list, puts the letter in a variable, and the value (if there is one) in $OPTARG. You call it in a while loop, so it keeps going until the options run out.
logsum v6
Here is the log tool with four options: -h for help, -q to be quiet, -s CLASS to count one status class, and -n COUNT to set how many top paths to show.
#!/usr/bin/env bash
# logsum v6: options with getopts
usage() {
echo "usage: logsum [-q] [-s CLASS] [-n COUNT] [-h] FILE..." >&2
}
quiet=0 class='' top=3
while getopts ':hqs:n:' opt; do
case $opt in
h) usage; exit 0 ;;
q) quiet=1 ;;
s) class=$OPTARG ;;
n) top=$OPTARG ;;
:) echo "logsum: -$OPTARG needs a value" >&2; usage; exit 2 ;;
\?) echo "logsum: unknown option -$OPTARG" >&2; usage; exit 2 ;;
esac
done
shift $((OPTIND - 1))
(( $# > 0 )) || { usage; exit 2; }
for log in "$@"; do
if [[ -n $class ]]; then
n=$(awk -v c="^$class" '$8 ~ c' "$log" | wc -l | tr -d ' ')
echo "$log: $n requests in class ${class}xx"
else
awk '{ print $6 }' "$log" | sort | uniq -c | sort -rn | head -n "$top"
fi
done
(( quiet )) || echo "done: $# file(s)" >&2
ShellCheck reported nothing. The option string ':hqs:n:' has three parts worth reading. The leading colon turns on silent mode, so getopts stays quiet about bad input and lets you write your own messages. The letters h and q are flags. s: and n: have a trailing colon, meaning they take a value. The case then handles each letter, plus two special cases that getopts produces in silent mode: ? for an unknown option, with the offending letter in $OPTARG, and : for an option whose value is missing.
It in action
$ ./logsum -n 2 logs/access.log
24 /about
23 /static/app.js
done: 1 file(s)
$ ./logsum -s 5 -q logs/access.log
logs/access.log: 24 requests in class 5xx
$ ./logsum -s5 logs/access.log
logs/access.log: 24 requests in class 5xx
done: 1 file(s)
$ ./logsum -qs 4 logs/access.log
logs/access.log: 32 requests in class 4xx
getopts is what makes -s5 and -s 5 equivalent, and what lets -qs 4 mean -q -s 4. The summary line goes to standard error, so -q can silence it without touching the real output. The numbers agree with the status-class totals from the case lesson: 24 in class 5xx, 32 in class 4xx.
Errors come out cleanly, with a non-zero status:
$ ./logsum -x logs/access.log; echo "status: $?"
logsum: unknown option -x
usage: logsum [-q] [-s CLASS] [-n COUNT] [-h] FILE...
status: 2
$ ./logsum -s; echo "status: $?"
logsum: -s needs a value
usage: logsum [-q] [-s CLASS] [-n COUNT] [-h] FILE...
status: 2
Printing the usage to standard error and exiting 2 follows the convention from the exit status lesson, where 2 means “misused”. -h printed the same usage and exited 0, since asking for help isn’t a failure. I ran this entire set under both Bash 3.2 and 5.3 and the output was identical.
OPTIND and shift
After the loop, $@ still contains the options. OPTIND is the index of the next argument to look at, so shift $((OPTIND - 1)) throws away what was parsed and leaves the file names in $1, $2, and so on. The script then checks (( $# > 0 )) to make sure it got a file. Skipping the shift is the most common getopts bug, because the loop appears to work and then the file list is wrong.
Where getopts stops
getopts stops at the first argument that isn’t an option. Options after a file name are never parsed:
$ ./logsum logs/access.log -q 2>&1 | tail -2
source line number 1
done: 2 file(s)
It counted two files, because -q was passed to awk as a file name and the awk error scrolled by on standard error. GNU tools often accept options anywhere, but getopts follows the POSIX rule that they come first. A -- marks the end of options explicitly, which lets you pass a file whose name starts with a dash.
It also handles short options only. There is no --verbose. There is an external getopt command that supports long options, but it differs between systems. On this Mac, getopt --version printed --, which is the signature of the old BSD getopt that doesn’t understand long options at all. GNU getopt on Linux does, so a script using it isn’t portable. For a small script, getopts is the dependable choice, and for long options a hand-written while and case over "$1" also works anywhere.
About the video
You Suck at Programming’s “Crash-Course in using getopts to parse Command Line Arguments in Bash!” by Dave Eddy is 4 minutes 59 seconds and was published in May 2025. The description says it was recorded during an Instagram live stream and points to help getopts in the shell for the full list of options, and I had no transcript or chapters. So the title is my only evidence that it covers option parsing, and at five minutes it is a quick tour, not a full treatment: the silent mode, OPTIND, the shift, and the stops-at-first-non-option behaviour in this lesson come from my own runs. It is in English. I searched for something with readable chapters and found nothing better. The other getopts videos I found were older, longer, or had descriptions with no content, and one three-hour user-group session had no chapters at all.
Where this fits
Options tell a script what to do. When it needs to ask a question or take a block of text, there is reading input and here documents.
Check yourself
In the option string `':hqs:n:'`, what do the leading colon and the trailing colons mean?
The leading colon enables silent error handling, so the script reports problems itself. A colon after a letter, such as `s:`, means that option takes a value, delivered in `$OPTARG`.
Why do you run `shift $((OPTIND - 1))` after the loop?
`OPTIND` is the index of the next argument to process. Shifting by one less than it discards the parsed options, so `$1` is the first real argument, such as a file name.
What happens to `./logsum logs/access.log -q`?
`getopts` stops at the first non-option word, `logs/access.log`, so `-q` is never parsed and is passed along as another argument. Put options before file names.
How do you support `--verbose` with `getopts`?
You can't directly, because it handles only single-letter options. Parse long options by hand with a `case` loop over `$1`, or use the external `getopt` while accepting its portability differences.
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.