0Pricing
Linux Command Line & Bash Scripting Mastery · Lesson

Parsing Flags and Arguments with getopts

Implement professional command-line interfaces using getopts for short options, required arguments, and usage messages.

Why getopts Exists

Every real-world script eventually needs to accept options like -v, -o output.txt, or -n 5. Parsing these by hand with $1, $2… becomes brittle fast.

getopts is the POSIX-standard built-in that handles short options (-a, -b) reliably, including options that take an argument. It is built into every POSIX shell, so no dependencies are required.

  • Handles combined flags: -vn 5 = -v -n 5
  • Reports unknown options gracefully
  • Sets standard variables OPTIND and OPTARG automatically

In this lesson you will build a complete, professional CLI using getopts from scratch.

The getopts Syntax

The core syntax is a while loop that calls getopts on every iteration:

while getopts "optstring" varname; do
  case "$varname" in
    ...
  esac
done
  • optstring — a string listing each accepted option letter. A colon after a letter means that option requires an argument.
  • varname — receives the current option letter on each iteration.
  • OPTARG — automatically set to the argument value when a colon follows the letter.
  • OPTIND — index of the next argument to process; shift with shift $((OPTIND - 1)) after the loop to expose remaining positional parameters.
#!/usr/bin/env bash
# Minimal skeleton — shows the loop structure
while getopts 'vn:' opt; do
  case "$opt" in
    v) echo "Verbose mode on" ;;
    n) echo "Count = $OPTARG" ;;
    ?) echo "Unknown option: -$OPTARG" >&2; exit 1 ;;
  esac
done

All lessons in this course

  1. Designing Functions with Local Scope and Return Codes
  2. Building and Sourcing Reusable Bash Libraries
  3. Parsing Flags and Arguments with getopts
  4. Passing Arrays and Associative Maps Between Functions
← Back to Linux Command Line & Bash Scripting Mastery