Parsing Options with getopts

Su Suriya Ravichandran Updated 06 Dec 2026
13 min read ·Lesson 130 of 205

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:

  • v is 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 (opt here);
  • 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 ? and OPTARG holds the unknown letter;
  • for a missing value, the variable is set to : and OPTARG holds 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 turn getopts' findings into the script's own usage messages and exit with status 2.
  • Validation follows the loop. -k must be 1 to 99; 10# accepts input such as 08 (lesson 128). At least one file is required.
  • run prints each command with printf %q (so names with spaces are visible) when -n or -v is given, and executes it unless -n was given. Implementing dry run in one function means no action can forget to respect it.
  • rotate_one moves 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.
  • || return after each step is needed because the function is called as rotate_one "$log" || status=1, and set -e is 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.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Parsing Options with getopts and get answers drawn from it.

Signed-in readers only.