getopts reads short command-line flags one at a time. Scripts use it to turn options into named variables.

Program

Play the script to watch -v -t docs update verbose and target.

getopts.sh
Replay: real traced execution (multi-file project)
#!/usr/bin/env bash

set -- -v -t docs
verbose=false
target="build"
while getopts "vt:" opt; do
  case "$opt" in
    v) verbose=true ;;
    t) target="$OPTARG" ;;
  esac
done
echo "$verbose:$target"
  1. $@ ← -v -t docs

    3set -- -v -t docs4verbose=false
    values this step-v -t docs$@
  2. verbose ← false

    3set -- -v -t docs4verbose=false5target="build"
    values this stepfalseverbose
  3. target ← build

    4verbose=false5target="build"6while getopts "vt:" opt; do
    values this stepbuildtarget
  4. opt ← v, OPTIND ← 2

    5target="build"6while getopts "vt:" opt; do7  case "$opt" in
    values this stepvopt2OPTIND
  5. verbose ← true

    7case "$opt" in8  v) verbose=true ;;9  t) target="$OPTARG" ;;
    values this steptrueverbose
  6. opt ← t, OPTARG ← docs, OPTIND ← 4

    5target="build"6while getopts "vt:" opt; do7  case "$opt" in
    values this steptoptdocsOPTARG4OPTIND
  7. target ← docs

    8  v) verbose=true ;;9  t) target="$OPTARG" ;;10esac
    values this stepdocstargetdocsOPTARG
  8. echo "$verbose:$target"

    11done12echo "$verbose:$target"
    outputtrue:docs
    values this steptrueverbosedocstarget

Follow the Flags

  1. set -- -v -t docs makes the script arguments -v -t docs.
  2. verbose starts as false, and target starts as build.
  3. First getopts sees opt=v with OPTIND=2, so verbose becomes true.
  4. Second getopts sees opt=t, OPTARG=docs, and OPTIND=4, so target becomes docs.
  5. The script prints true:docs. | pass | opt | OPTARG | OPTIND | result | | --- | --- | --- | --- | --- | | start | - | - | - | verbose=false, target=build | | 1 | v | - | 2 | verbose=true | | 2 | t | docs | 4 | target=docs | | stdout | - | - | - | true:docs |
getopts `getopts` parses short flags such as `-v` and options with values such as `-t docs`.
OPTARG `OPTARG` holds the value attached to the current option.

Exercise: getopts.sh

Reproduce true:docs, then identify which option changes verbose and which option changes target.