Script Valley
Bash Scripting for Developers
Functions and Script ArchitectureLesson 3.5

Bash argument parsing with getopts

getopts vs getopt, short option syntax, option with argument, OPTARG OPTIND, error handling in getopts, required vs optional arguments, help flag pattern, shift after getopts

Parsing Flags with getopts

getopts argument parsing flow

getopts is the built-in, POSIX-portable way to parse short flags (-v, -o file). For long flags (--verbose) you need getopt (external) or a manual case loop.

#!/usr/bin/env bash
set -euo pipefail

usage() {
  echo "Usage: $0 [-v] [-o output_dir] [-e env] input_file"
  exit 0
}

verbose=false
output_dir="./output"
environment="dev"

# Leading colon = silent error handling (we handle errors)
while getopts ":vo:e:h" opt; do
  case "$opt" in
    v) verbose=true ;;
    o) output_dir="$OPTARG" ;;
    e) environment="$OPTARG" ;;
    h) usage ;;
    :) echo "Option -$OPTARG requires an argument" >&2; exit 1 ;;
    ?) echo "Unknown option: -$OPTARG" >&2; exit 1 ;;
  esac
done

# Shift past parsed options to reach positional args
shift $(( OPTIND - 1 ))
input_file="${1:-}"

[[ -z "$input_file" ]] && { echo "Error: input file required" >&2; exit 1; }

$verbose && echo "Verbose mode ON"
echo "Input: $input_file, Output: $output_dir, Env: $environment"

The colon after a letter in the optstring (o:) means that option requires an argument. A leading colon on the optstring enables silent mode where you handle : and ? cases yourself, giving better error messages.