Code Reference

getopts

Bash · Reference cheat sheet

getopts

Bash · Reference cheat sheet


📋 Overview

getopts parses single-letter command-line options in a portable way. It handles clustered flags (-abc), optional/required arguments, and error reporting. For long options (--verbose), use a manual loop or external tools—not plain getopts.

🔧 Core concepts

PieceRole
getopts optstring nameParse next option into name
optstringLetters; append : if option requires an argument
Leading : in optstringSilent error mode (? / : in name)
$OPTARGArgument value or bad option letter
$OPTINDNext argv index to process
--End of options (caller convention)

After the loop, remaining operands are "$@" shifted with shift $((OPTIND - 1)).

💡 Examples

Classic flags:

#!/usr/bin/env bash
verbose=0
file=""

while getopts ':vf:' opt; do
  case "$opt" in
    v) verbose=1 ;;
    f) file="$OPTARG" ;;
    :) echo "option -$OPTARG requires an argument" >&2; exit 2 ;;
    ?) echo "unknown option -$OPTARG" >&2; exit 2 ;;
  esac
done
shift $((OPTIND - 1))

echo "verbose=$verbose file=$file args: $*"

Usage pattern:

usage() {
  cat <<'EOF' >&2
usage: tool [-v] [-f file] [args...]
EOF
  exit 2
}

Reset for reuse (functions):

OPTIND=1

⚠️ Pitfalls

  • getopts does not parse --long options.
  • Missing required args: with silent mode, opt is : and OPTARG is the option letter.
  • Forgetting shift $((OPTIND - 1)) leaves flags in "$@".
  • OPTIND is global—reset when calling getopts multiple times.
  • Option arguments starting with - are still accepted as OPTARG.
  • Prefer getopts over hand-rolled $# loops for short options.

On this page