$_ CLI In Depth
Learning progress 0%
lesson scripting exit-codes control-flow

Option Parsing with getopts

6 min read Module 13: Scripting Basics & Exit Codes Updated Dec 5, 2026
Cheat Sheet
0:00 / 3:16

The option string

The getopts builtin parses the arguments of a script according to an option string. Each letter in the string is a flag that the script accepts. A letter followed by a colon takes a value. The string vn: means the script accepts -v as a flag and -n with a value. Option names are single characters, so long options such as --verbose are outside what getopts handles.

The getopts command is a shell builtin, so it is available in every bash script without installing anything. The separate getopt program from util-linux can handle long options, but it is not portable, and scripts that need only short options usually choose getopts. The getopt(3) manual page describes the C function that these conventions come from.

A loop with getopts

The usual pattern is a while loop around getopts, with a case statement on the option letter. The getopts command stores the current letter in the variable you name. It returns status 0 while options remain, and status 1 when it runs out of them.

BASH7 lines
verbose=0
while getopts "vn:" opt; do
  case $opt in
    v) verbose=1 ;;
    n) name=$OPTARG ;;
  esac
done

Set the defaults before the loop, so that options the caller leaves out keep their values. Each letter in the case must match the option string exactly. A flag sets a variable, and a value option copies the value from OPTARG into a variable. Quoting the option string is a good habit, even though it contains no characters that the shell would expand.

Values, OPTARG and OPTIND

For an option that takes a value, getopts stores the value in OPTARG. Both -n ana and -nana work, because getopts accepts the value attached to the letter as well as the value in the next word. The variable OPTIND holds the index of the next argument to process. It starts at 1 and advances as options are consumed.

Every option that takes a value must consume it, and getopts does that for you. The value after -n is never mistaken for a file name, even when it looks like an option. For instance, -n -v stores the text -v as the name, because the colon in the option string tells getopts that the next word belongs to -n. A script that wants to reject values that start with a hyphen has to check OPTARG itself after the loop.

Bundled flags work too. The input -vn ana is read as -v followed by -n with the value ana. This is the same convention that tar and ls follow. Each letter in a bundle is a separate option, and the loop visits them in order.

Removing the options

When the loop ends, the options are still among the positional parameters. Remove them with shift $((OPTIND - 1)), which drops everything getopts consumed. After that, $1 is the first file name or other plain argument, and $# counts only those. The value of OPTIND tells you how many words to skip, which is why the line is written this way.

BASH4 lines
shift $((OPTIND - 1))
for file in "$@"; do
  echo "$file"
done

Errors and the leading colon

An unknown option makes getopts set opt to a question mark, and it stores the offending letter in OPTARG. A missing value makes opt a colon, with the option letter in OPTARG. By default bash also prints its own message to standard error. A case branch for the question mark and the colon lets you print your usage text and exit with status 2 instead.

If the option string starts with a colon, as in :vn:, getopts runs in silent mode. It stops printing its own messages, and it reports a missing value with the colon. Silent mode gives the script full control of the message, which is the reason to choose it for tools that have a fixed usage format.

The end of options

A double dash, --, ends the options explicitly. Anything after it is a plain argument, even if it starts with a hyphen. This is how you pass a file named -notes to a script. The getopts command stops at the double dash and consumes it, so the shift removes it too.

Designing the flags of a tool

Choosing which options to add is a design decision, and getopts makes the mechanics easy. Keep flags for choices that are on or off, such as verbose output. Use a value option when the caller must supply information, such as a name or a path. Give every option a single letter that matches the first letter of its meaning, when you can, so that the script is easy to remember. Document the options in the usage line, because the usage line is the first thing a user reads when a call goes wrong.

Defaults belong before the loop, and they should be the safest values. A verbose flag that defaults to off keeps normal output quiet. A name that defaults to a neutral value is easier to test than one that reads the current user. When a default could cause harm, such as deleting files, make the caller ask for it explicitly.

Order of options is not important to getopts. The script sees -v -n ana and -n ana -v as the same request, and it can treat the remaining words as its input in either case. This flexibility is one reason getopts is preferred over reading $1 directly, which would force a fixed order on callers.

Hands-on: a small greeter

The block below shows the pattern on a small scale, with a usage branch for unknown options. Use it as a starting point rather than a finished tool.

BASH16 lines
cat > greet.sh << 'EOF'
verbose=0
name=anon
while getopts "vn:" opt; do
  case $opt in
    v) verbose=1 ;;
    n) name=$OPTARG ;;
    *) echo "usage: greet.sh [-v] [-n NAME]" >&2; exit 2 ;;
  esac
done
shift $((OPTIND - 1))
echo "verbose=$verbose name=$name"
EOF
bash greet.sh -v -n ana
bash greet.sh -vnana
bash greet.sh -x

The first two calls print the same line, because -vnana is the bundled form of -v -n ana. The last call prints the usage line and exits with status 2, which is the convention for misuse of a command.

Stepping through getopts

Visualizer

getopts reads one option per call and keeps its place in OPTIND. Watch -v -o out.txt -- file split into flags, an argument and the operands that remain.

1 / 6
set -- -v -o out.txt -- file
-v$1
-o$2
out.txt$3
--$4
file$5
OPTIND
1
opt
(none yet)
OPTARG
(unset)

getopts keeps its place in OPTIND, which starts at 1. Each call handles one option letter and stores it in opt.

OPTIND=1; unset OPTARG; set -- -v -o out.txt -- file; while getopts "vo:" opt; do echo "opt=$opt OPTARG=$OPTARG OPTIND=$OPTIND"; done; shift $((OPTIND-1)); echo "rest: $*"
Terminal lab · 2 steps · real Linux in your browser

Parse flags with getopts

Parse a flag and a value option with getopts, then reject unknown options with usage and status 2.

01
Parse flags and a value
Create opts.sh in /workspace. It accepts -v as a flag that turns verbose on, and -n followed by a value that sets a name. Use getopts with the option string vn:. The defaults are verbose=0 and name=anon. After the options, remove them with shift and print one line: verbose=V name=N files=C, where C is the number of arguments left. Test it with -v -n ana a b, with no arguments, and with -n bo x.
Show hint for step 1
Use while getopts with a case on the option letter. After the loop, shift $((OPTIND - 1)) before you count the remaining arguments.
02
Reject unknown options with usage
Update opts.sh so that an unknown option, or an option that is missing its value, is an error. In either case print usage: opts.sh [-v] [-n NAME] [FILE...] to standard error and exit with status 2. Valid options keep working as before. Test an unknown option such as -x and a missing value such as a bare -n.
Show hint for step 2
getopts sets the variable to a question mark for an unknown letter, and to a colon when a value is missing. A catch-all branch in the case covers both.
Check yourself Question 1 of 4
Concept Check Meaning of the colon in an option string recall

In the option string vn:, what does the colon after n mean?

Recap & Key Takeaways

getopts parses one option at a time from an option string, where a letter followed by a colon takes a value stored in OPTARG.
After the loop, shift $((OPTIND - 1)) removes the parsed options, so $1 becomes the first plain argument.
An unknown option gives a question mark and a missing value gives a colon, and a case branch for both can print usage and exit with status 2.
A double dash ends the options, so an argument that starts with a hyphen can still be passed as a plain argument.
Was this lesson helpful? Spot an issue or have a suggestion? Let us know on GitHub.
Report an issue