Skip to content
$ lynuxpro
← Bash Scripting

LESSON 12 OF 17 · ADVANCED · 16 MIN

Parsing options with getopts

HOW IT WORKSHow getopts reads command-line options

./deploy.sh -v -e prod webgetopts "ve:h"one option per call-vverbose=1-e prodenv=$OPTARG-x? → usageshift $((OPTIND-1))drop options$1 = webwhat's left
1/5

Scripts that grow need options. getopts reads them one at a time in a while loop.

while getopts "ve:h" opt; do

Once a script has more than two or three inputs, positional arguments get confusing. Was it ./deploy.sh prod checkout 3 or ./deploy.sh checkout 3 prod? Real tools use options: -e prod -r 3 -v checkout. Order stops mattering, defaults are obvious and -h explains everything. Bash's built-in getopts parses short options correctly with a few lines of code.

In simple words

  • Option: a flag that changes how the script behaves, such as -v or -f file.
  • getopts: Bash's built-in helper for reading short options safely.
  • Usage function: prints how to use the script, shown on -h or on a mistake.
  • Dry run: a mode that shows what the script would do without changing anything.

Options, values and operands

./deploy.sh -v -e prod -r 3 checkout             │  │       │    └── operand (a normal argument)             │  │       └── option with a value             │  └── option with a value             └── flag (an option without a value)
OUTPUTterminalutf-8 · 5L

Conventions every Unix user expects:

  • Short options are a dash and one letter: -v.
  • Flags can be combined: -vf is the same as -v -f.
  • A value can be attached or separate: -eprod or -e prod.
  • -- ends the options; everything after it is an operand, even if it starts with -.
  • -h prints help.

getopts handles all of these for you.

The getopts loop

#!/usr/bin/env bashverbose=0env=stagingreplicas=2 while getopts ":ve:r:h" opt; do  case "$opt" in    v) verbose=1 ;;    e) env=$OPTARG ;;    r) replicas=$OPTARG ;;    h) echo "usage: $0 [-v] [-e ENV] [-r N] APP"; exit 0 ;;    :) echo "option -$OPTARG needs a value" >&2; exit 2 ;;    \?) echo "unknown option -$OPTARG" >&2; exit 2 ;;  esacdoneshift $((OPTIND - 1)) app=${1:?usage: $0 [-v] [-e ENV] [-r N] APP}echo "app=$app env=$env replicas=$replicas verbose=$verbose"
SHELLbashutf-8 · 19L

How it works:

  • The option string ":ve:r:h" lists the letters you accept. A letter followed by : takes a value (e: and r:); a letter without one is a flag.
  • Each call to getopts reads the next option, puts its letter in $opt, and returns 0. When there are no more options it returns non-zero and the while loop ends.
  • $OPTARG holds the value of options that take one.
  • The leading : turns on "silent" error mode, so you print the messages: an unknown option gives opt=? and a missing value gives opt=:, with the offending letter in $OPTARG. Without the leading colon, getopts prints its own generic errors.
  • $OPTIND is the index of the next argument to process. After the loop, shift $((OPTIND - 1)) removes all the options, so the operands start at $1 again.

Try it

Create the script in the practice terminal and run it with different arguments:

printf '#!/usr/bin/env bash\nverbose=0; env=staging; replicas=2\nwhile getopts ":ve:r:h" opt; do\n  case "$opt" in\n    v) verbose=1 ;;\n    e) env=$OPTARG ;;\n    r) replicas=$OPTARG ;;\n    h) echo "usage: $0 [-v] [-e ENV] [-r N] APP"; exit 0 ;;\n    :) echo "option -$OPTARG needs a value" >&2; exit 2 ;;\n    \\?) echo "unknown option -$OPTARG" >&2; exit 2 ;;\n  esac\ndone\nshift $((OPTIND - 1))\napp=${1:-}\n[[ -n $app ]] || { echo "missing APP" >&2; exit 2; }\necho "app=$app env=$env replicas=$replicas verbose=$verbose"\n' > deploy.shchmod +x deploy.sh./deploy.sh checkout./deploy.sh -v -e prod -r 4 checkout./deploy.sh -ve prod checkout./deploy.sh -eprod -r3 checkout
SHELLbashutf-8 · 6L
app=checkout env=staging replicas=2 verbose=0app=checkout env=prod replicas=4 verbose=1app=checkout env=prod replicas=2 verbose=1app=checkout env=prod replicas=3 verbose=0
OUTPUTterminalutf-8 · 4L

All four calls were parsed correctly, including the combined -ve prod and the attached -eprod. Now the error cases:

./deploy.sh -x checkout./deploy.sh -e./deploy.sh -h
SHELLbashutf-8 · 3L
unknown option -xoption -e needs a valueusage: ./deploy.sh [-v] [-e ENV] [-r N] APP
OUTPUTterminalutf-8 · 3L

Validating option values

getopts checks the shape of the command line, not the values. Validate those after the loop:

case "$env" in  dev|staging|prod) ;;  *) echo "invalid -e '$env' (expected dev, staging or prod)" >&2; exit 2 ;;esac if [[ ! $replicas =~ ^[0-9]+$ ]] || (( replicas < 1 || replicas > 20 )); then  echo "invalid -r '$replicas' (expected 1-20)" >&2  exit 2fi
SHELLbashutf-8 · 9L

A proper usage function

Help text is part of the interface. Put it in a function, print it for -h (to stdout, exit 0) and for errors (to stderr, exit 2):

usage() {  cat <<EOFUsage: ${0##*/} [options] APPDeploy APP to an environment.Options:  -e ENV     target environment: dev, staging, prod (default: staging)  -r N       number of replicas, 1-20 (default: 2)  -n         dry run: print what would happen  -v         verbose output  -h         show this helpExamples:  ${0##*/} checkout  ${0##*/} -e prod -r 4 checkoutEOF}
SHELLbashutf-8 · 18L

Then: h) usage; exit 0 ;; and \?) usage >&2; exit 2 ;;.

Repeated options

Some options make sense more than once, like -v -v for more verbosity or -t a -t b for several tags. Count or collect them:

printf '#!/usr/bin/env bash\nlevel=0; tags=()\nwhile getopts "vt:" o; do\n  case $o in\n    v) level=$((level + 1)) ;;\n    t) tags+=("$OPTARG") ;;\n  esac\ndone\necho "verbosity=$level tags=${tags[*]}"\n' > multi.shchmod +x multi.sh./multi.sh -vv -t web -t canary
SHELLbashutf-8 · 3L
verbosity=2 tags=web canary
OUTPUTterminalutf-8 · 1L

What getopts does not do: long options

getopts only understands single-letter options. For --env prod or --dry-run, you have three choices:

  1. Keep to short options. Simple and portable; fine for most internal scripts.
  2. Write a manual while loop with case, which handles long options and is very readable:
while [[ $# -gt 0 ]]; do  case "$1" in    -e|--env)      env=${2:?--env needs a value}; shift 2 ;;    --env=*)       env=${1#*=}; shift ;;    -n|--dry-run)  dry_run=1; shift ;;    -v|--verbose)  verbose=1; shift ;;    -h|--help)     usage; exit 0 ;;    --)            shift; break ;;    -*)            echo "unknown option $1" >&2; usage >&2; exit 2 ;;    *)             break ;;  esacdone
SHELLbashutf-8 · 12L
  1. Use the external getopt (no "s", from util-linux), which supports long options but behaves differently across systems. Avoid it in portable scripts.

The manual loop is what many popular open-source Bash tools use. Its trade-off is that combined flags like -vn are not split for you.

A dry-run flag

A -n / --dry-run flag that prints commands instead of running them makes any destructive script much safer to use and to review. A tiny helper does it:

dry_run=1run() { if [[ $dry_run == 1 ]]; then echo "+ $*"; else "$@"; fi; }run kubectl scale deploy/checkout --replicas=4 -n prodrun rm -rf /tmp/release-old
SHELLbashutf-8 · 4L
+ kubectl scale deploy/checkout --replicas=4 -n prod+ rm -rf /tmp/release-old
OUTPUTterminalutf-8 · 2L

Wrap every command that changes something in run, and reviewers can see exactly what the script will do before it does it.

Real-world scenario: one script, many environments

A platform team had five near-identical scripts, deploy-dev.sh, deploy-staging.sh, deploy-prod.sh and so on, that drifted apart over time. They replaced them with one script:

deploy.sh -e prod -r 4 -t 2.4.1 -n checkout
OUTPUTterminalutf-8 · 1L
  • -e chose the environment, validated against a list.
  • -r and -t set replicas and image tag, with sensible defaults.
  • -n printed every kubectl command without running it, which became a required step in their change review.
  • -h documented everything, so new team members stopped asking how to deploy.

One script meant one place to fix bugs, and -n output pasted into the change ticket made production deploys much easier to approve.

Common mistakes

  • Forgetting shift $((OPTIND - 1)): operands stay mixed with options.
  • Missing : after a letter that needs a value: $OPTARG is empty and the value becomes an operand.
  • Putting operands before options: getopts stops at the first non-option, so ./deploy.sh checkout -e prod ignores -e prod. Document "options first".
  • Forgetting \? in the case (the ? must be escaped or quoted, or it matches any single character).
  • Not resetting OPTIND=1 when using getopts inside a function that is called more than once.
  • Expecting long options from getopts.

Practice

  1. Write backup.sh that accepts -s SOURCE, -d DEST, -k DAYS (default 7) and -n for dry run, then prints the settings.
  2. Make it fail with a clear message when -s or -d is missing.
  3. Add a usage function with a here-document and wire it to -h and to errors.
  4. Validate that -k is a positive number.
  5. Rewrite the parsing with a manual while/case loop that also accepts --source, --dest and --dry-run.

Cheat sheet

while getopts ":ab:c:h" opt; do      a = flag, b: and c: take values  case $opt in    a) … ;;    b) val=$OPTARG ;;    h) usage; exit 0 ;;    :) echo "-$OPTARG needs a value" >&2; exit 2 ;;    \?) echo "unknown -$OPTARG" >&2; exit 2 ;;  esacdoneshift $((OPTIND - 1))                 operands now start at $1OPTIND=1                              reset before reusing getoptscase $1 in --long=*) v=${1#*=} ;; esac   manual long optionsrun() { [[ $dry_run == 1 ]] && echo "+ $*" || "$@"; }
OUTPUTterminalutf-8 · 13L

Key takeaways

  • Options make scripts self-explanatory and order-independent; getopts parses short options, combined flags and attached values.
  • The option string lists letters, with : after those that take a value; a leading : lets you print your own errors.
  • Always shift $((OPTIND - 1)) after the loop, then validate values separately.
  • Provide -h with a clear usage text, and a -n dry-run mode for anything destructive.
  • For long options, write a manual while/case loop.