Parse options and arguments in Bash scripts
8 steps · about 2 h 15 min · Intermediate
- Follow the standard utility argument conventions (reference, The Open Group, 15 min)
POSIX defines how options, option-arguments and -- should behave, so your script matches users' expectations.
- Read the getopts specification (reference, The Open Group, 15 min)
Defines OPTIND, OPTARG and silent error mode with a worked example.
- Compare getopts with a manual while loop (article, Greg's Wiki, 20 min)
Shows both patterns, including long options, and the pitfalls of external getopt.
- Work with $1, $2, shift and set -- (article, The Linux Documentation Project, 15 min)
Worked examples of positional parameters, which getopts and shift operate on.
- Use $#, $@ and $* correctly (reference, The Open Group, 20 min)
The POSIX shell language section on special parameters explains why quoted "$@" preserves arguments with spaces.
- Know OPTIND, OPTARG and OPTERR (reference, man7.org, 15 min)
The bash man page documents the variables getopts reads and sets, and the getopts builtin itself.
- Know when util-linux getopt is an option (reference, man7.org, 10 min)
Supports long options but is not portable; the man page shows the safe eval pattern.
- Design helpful usage text and errors (article, clig.dev, 25 min)
Command Line Interface Guidelines on help output, flags versus args and error messages.