Parse Flags With getopts

Handle short options and option arguments in a portable shell loop.

macOSbashautomationshellscriptingLow risk
Use while getopts "vn:" opt to read -v and -n <value> into variables.

01Command

Command
$ while getopts "vn:" opt; do case $opt in v) verbose=1;; n) name=$OPTARG;; esac; done

02What it does

getopts implements the standard Unix option grammar inside the shell, including clustering and required arguments, so scripts accept flags the same way system tools do. Writing an option parser by hand is error-prone, and no GUI can offer this contract.

03Risk

RiskLow risk
RequirementsmacOS default zsh/bash (bash 3.2+; some features need bash 4+ via Homebrew)
CompatibilitymacOS with bash 3.2+ (GNU bash 4+ via Homebrew for advanced features)
!Warning: getopts handles short options only; long options such as --verbose need manual parsing or getopt from util-linux.

04Undo

✓No undo needed — this command does not change persistent state.

05Sources

Last verified: 2026-10-13 · Category: Developer