Option Parsing with getopts

Option Parsing with getopts in Bash: --- Picture an officer at a customs declarations desk at a port.


The Analogy: The Customs Declarations Desk

Picture an officer at a customs declarations desk at a port. A traveller hands over a single slip covered in short codes -- a v for "value goods", a d followed by a written amount for "duty to declare", a b for "business trip". The officer does not improvise; they work from a laminated rulebook that lists exactly which codes are valid and, crucially, which ones must be followed by a written value. Codes that stand alone are simple ticks. Codes marked in the rulebook with a colon beside them are incomplete without an attached figure, and the officer expects that figure to come right after the code. This rulebook is the getopts optstring: a compact string like "vd:b" where a letter alone is a flag and a letter followed by a colon is an option that demands a value.

As the officer reads the slip, they process one code at a time and keep a finger on their place so they always know which code comes next. That place-keeping finger is OPTIND, the index of the next argument to examine. When a code requires a value -- the d with its duty figure -- the officer copies that figure into a working box on their form; in getopts that working box is OPTARG, which holds the value of the option currently being processed. Several simple codes squeezed together on one line, like vb written as a single group, do not confuse the officer: they read it as v then b, exactly as getopts unbundles -vb into two separate flags.

The rulebook also dictates how the officer reacts to trouble, and there are two modes. In the loud mode, the officer announces every problem directly to the hall -- "invalid code on this slip!" -- which is what getopts does by default, printing its own error messages. In the quiet mode, chosen by putting a colon at the very front of the rulebook, the officer says nothing aloud and instead silently records the problem in a specific box for the back office to handle: an unrecognised code is filed under ? and a code missing its required figure is filed under :, with the offending letter placed in OPTARG. Experienced desks run in quiet mode so they control exactly what the traveller is told.

The failure mode is a code that the rulebook says needs a figure but which arrives with nothing after it -- a d at the very end of the slip with no duty amount written. In loud mode the officer blurts a generic complaint; in quiet mode they file it under : so your code can print a precise "the -d option needs a value" and reject the slip cleanly. A second, subtler trap is that the officer only reads codes until the first line that is plainly not a code -- once the traveller starts listing actual goods, the officer stops looking for codes, so a code written after the goods list is treated as a good, not an instruction. That is why getopts stops at the first non-option argument, and why options must come before positional arguments.


Syntax or Core Structure

getopts is a shell builtin that parses single-letter options from the positional parameters. You call it in a while loop: getopts optstring name sets name to the next option letter and returns success until the options run out. A letter followed by a colon in the optstring takes a value, delivered in OPTARG. After the loop, shift $((OPTIND - 1)) discards the parsed options and leaves the positional arguments.

#!/usr/bin/env bash
set -- -v -o result.txt deploy prod
verbose=0
output="out.txt"
while getopts "vo:" opt; do
  case $opt in
    v) verbose=1 ;;
    o) output=$OPTARG ;;
  esac
done
shift $(( OPTIND - 1 ))
echo "verbose=$verbose"
echo "output=$output"
echo "remaining: $*"

Output:

verbose=1
output=result.txt
remaining: deploy prod

The set -- line loads a fixed argument list so the demonstration is reproducible. The optstring "vo:" says -v is a flag and -o takes a value. The loop runs twice: first opt is v and verbose becomes 1, then opt is o and OPTARG holds result.txt, which is copied into output. When getopts reaches deploy, which does not start with a dash, it returns failure and the loop ends with OPTIND pointing at deploy. The shift $(( OPTIND - 1 )) then drops the three consumed option words, leaving deploy prod as the positional arguments -- the actual operands the command should act on.


Technical Depth: Bundling, Attached Values, and Error Modes

The getopts vocabulary

Five pieces of state and syntax carry all of getopts. The optstring configures what is accepted; the two variables report what was found.

ItemRole
optstring lettersthe option letters getopts will accept
a letter then colonthat option requires a value argument
a leading colonsilent error mode; you handle the ? and : cases
OPTARGvalue of a value-taking option, or the bad letter on error
OPTINDindex of the next argument getopts will look at

Bundled flags and attached values

getopts handles the compact forms that users expect from Unix tools: several flags bundled behind one dash, and a value attached directly to its option letter. Declaring local OPTIND inside a function is essential so each call parses from a fresh position.

#!/usr/bin/env bash
parse() {
  local v=0 n=0 out="-"
  local OPTIND opt
  while getopts "vno:" opt; do
    case $opt in
      v) v=1 ;;
      n) n=1 ;;
      o) out=$OPTARG ;;
    esac
  done
  echo "v=$v n=$n out=$out"
}
parse -vn -o file1
parse -o file2 -v
parse -vofile3

Output:

v=1 n=1 out=file1
v=1 n=0 out=file2
v=1 n=0 out=file3

The first call bundles -vn -- getopts unpacks it into -v and -n -- and takes file1 as the value of -o. The second call proves order does not matter: -o file2 then -v sets both. The third call, -vofile3, shows the attached form: after the flag v, the o consumes the rest of the word, file3, as its value with no space needed. The local OPTIND declaration matters enormously here: without it, OPTIND would retain its value from the previous call and the second and third parse calls would start parsing from the wrong position or not at all.

Silent error mode

Putting a colon at the front of the optstring switches off getopts's built-in error messages and routes problems to two special cases: ? for an unknown option and : for a missing required value, with the offending letter in OPTARG. This gives you full control over the wording.

#!/usr/bin/env bash
parse() {
  local OPTIND opt
  while getopts ":a:b" opt; do
    case $opt in
      a) echo "  a with value: $OPTARG" ;;
      b) echo "  b flag" ;;
      :) echo "  missing arg for -$OPTARG" ;;
      ?) echo "  unknown option -$OPTARG" ;;
    esac
  done
}
echo "case1: -b -a hi"; parse -b -a hi
echo "case2: -a (missing value)"; parse -a
echo "case3: -x (unknown)"; parse -x

Output:

case1: -b -a hi
  b flag
  a with value: hi
case2: -a (missing value)
  missing arg for -a
case3: -x (unknown)
  unknown option -x

Case one parses normally: the b flag then the a option with value hi. Case two supplies -a with nothing after it; because a requires a value, the leading-colon mode sets opt to : and OPTARG to a, so the : case prints a precise missing-argument message. Case three passes -x, which is not in the optstring, so opt becomes ? and OPTARG becomes x. The \? in the case pattern is an escaped literal question mark. Without the leading colon, getopts would have printed its own generic errors to standard error and set opt to ? for both problems, giving you less control over the message and no easy way to distinguish a missing value from an unknown flag.


Real World Example: A Backup Command With Options and Operands

A realistic command mixes flags, value-taking options, and positional operands. This backup skeleton accepts -v (verbose), -n (dry run), -d DIR (destination), -k KEEP (retention count), and -h (help), then treats everything remaining as the targets to back up. It parses in silent mode so its error messages are its own.

#!/usr/bin/env bash
set -u

usage() { echo "usage: backup [-v] [-n] [-d DIR] [-k KEEP] target..."; }

main() {
  local verbose=0 dry=0 dir="/var/backups" keep=7
  local OPTIND opt
  while getopts ":vnd:k:h" opt; do
    case $opt in
      v) verbose=1 ;;
      n) dry=1 ;;
      d) dir=$OPTARG ;;
      k) keep=$OPTARG ;;
      h) usage; return 0 ;;
      :) echo "option -$OPTARG needs a value" >&2; return 2 ;;
      ?) echo "unknown option -$OPTARG" >&2; return 2 ;;
    esac
  done
  shift $(( OPTIND - 1 ))
  if (( $# == 0 )); then echo "no targets given" >&2; return 2; fi
  echo "plan:"
  echo "  dir     = $dir"
  echo "  keep    = $keep"
  echo "  verbose = $verbose"
  echo "  dry-run = $dry"
  echo "  targets = $*"
}

main -v -k 3 -d /srv/snap alpha beta

Output:

plan:
  dir     = /srv/snap
  keep    = 3
  verbose = 1
  dry-run = 0
  targets = alpha beta

Trace the parse. -v sets verbose, -k 3 sets keep from OPTARG, and -d /srv/snap sets dir. When getopts reaches alpha, parsing stops and shift $(( OPTIND - 1 )) removes the five consumed option words, leaving alpha beta as the targets. The n and h options were not given, so dry stays 0 and no usage message prints. The empty-target guard would have rejected a call with only options, and the silent-mode : and \? cases give clean, specific errors for a missing value or an unknown flag. This is the standard shape of a well-behaved Bash command: options first, validated, then operands.

The skeleton has three genuine limitations to know before shipping it. First, getopts validates that -k has a value but never that the value is a number: -k abc is accepted and stored as the string abc, and a later (( keep > 0 )) test would treat it as zero, so any value-taking option needs its own type check after parsing. Second, getopts is single-character only: there is no way to add --verbose or --keep long options, so tools that want them must parse by hand or use the external getopt program with its own pitfalls. Third, getopts stops at the first operand, so backup alpha -v does not enable verbose -- the -v after alpha is taken as a second target -- which surprises users accustomed to GNU tools that permute options and operands freely.


Common Mistakes

  1. Forgetting to declare local OPTIND in a function. OPTIND persists between getopts loops, so a function that parses options without local OPTIND starts from wherever the last parse left off and silently misreads its arguments on the second call. Always declare local OPTIND in any function that runs getopts.
  1. Omitting the shift after the loop. Without shift $(( OPTIND - 1 )), the positional parameters still include the parsed options, so $1 is -v rather than the first operand. The shift is what separates options from the operands the command should act on.
  1. Putting the colon in the wrong place. A colon after a letter means that option takes a value; a colon at the very front of the optstring means silent error mode. Confusing the two -- writing ":v" when you meant "v:" -- changes both which options take values and how errors are reported.
  1. Not handling the ? and : cases. In silent mode, an unknown option sets opt to ? and a missing value sets it to :. A case statement that omits these lets bad input fall through unhandled, so the command proceeds with default values instead of rejecting the mistake.
  1. Assuming getopts validates value types. getopts checks only that a required value is present, not that it is a number, a path, or anything specific. A value like -k abc passes parsing untouched; you must validate OPTARG yourself after capturing it.
  1. Expecting long options to work. getopts is strictly single-character; --verbose is not parsed as the v option and appears as an unknown option or an operand. If long options are required, parse them by hand or use a different tool.
  1. Placing options after operands. getopts stops at the first argument that is not an option, so cmd file -v never sees -v. Options must precede operands; document this, since users of GNU tools expect free intermixing.
  1. Reusing OPTIND without resetting it at the top level. In a script that parses arguments more than once, or re-parses after modifying the argument list, OPTIND must be reset to 1 before the second getopts loop, or parsing resumes from the stale index.
  1. Printing usage to standard output on error. Error and usage messages triggered by bad input belong on standard error with >&2, and the command should exit non-zero. Sending them to standard output pollutes any pipeline consuming the command and hides the failure from scripts checking the exit status.

Best Practices

  • Always declare local OPTIND inside functions. This resets the parse position for each call and is the single most important habit for using getopts in functions. Pair it with a local opt so the loop variable does not leak either.
  • Use silent error mode and handle ? and :. Start the optstring with a colon and write explicit ? and : cases so your command controls its own error wording and can distinguish an unknown option from a missing value. It reads better and tests more precisely.
  • Shift off the options before touching operands. Run shift $(( OPTIND - 1 )) immediately after the loop so the remaining positional parameters are exactly the operands. Then validate their count before use.
  • Validate OPTARG values after capturing them. Because getopts checks only presence, add a type or range check for each value-taking option -- confirm a count is numeric, a path exists, a mode is one of a known set -- and fail with a clear message otherwise.
  • Provide a usage function and an -h option. A single usage function printed by -h and reused in error paths keeps the help text consistent and gives users a quick reference. Route it to standard output for -h and to standard error for parse failures.
  • Document that options precede operands. Since getopts does not permute, state in the usage line and help text that options must come first. This sets expectations for users migrating from tools that allow intermixing.
  • Keep option letters mnemonic and few. getopts is happiest with a small set of single letters; when a command grows many options, that is a signal to reconsider its scope or move to a tool that supports long, self-documenting option names.
  • Send diagnostics to standard error and exit non-zero. Every parse failure should write to >&2 and return a non-zero status so pipelines and calling scripts can detect the error, keeping standard output reserved for real results.

Practice Exercises

  1. A three-option command. Write a script that accepts -v (flag), -o FILE (value), and -h (help), parses in silent mode, handles the unknown-option and missing-value cases, and after the loop shifts and prints the remaining operands. Test it with bundled flags and with the attached-value form -ofile.
  1. Value validation. Extend a parser so that a -n COUNT option requires its value to be a positive integer. After capturing OPTARG, validate it and print a specific error to stderr with a non-zero return when it is not numeric. Demonstrate both a valid and an invalid value.
  1. Function-local parsing. Write two functions that each parse their own options with getopts, and call both from one script. Show that declaring local OPTIND makes each parse independent, then remove it from one function and demonstrate the resulting misparse on the second call.
  1. Options-before-operands. Write a command that takes a -v flag and one or more file operands, and demonstrate that cmd -v a b enables verbose while cmd a b -v does not. Explain in a comment why getopts behaves this way and how it differs from GNU option permutation.