Parse Flags With getopts
Handle short options and option arguments in a portable shell loop.
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; done02What 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
!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
- bash.1.en.html manual pageEvidence: The bash manual page documents getopts.
Last verified: 2026-10-13 · Category: Developer