Bash getopts Script Builder
Scaffold POSIX-compliant, error-hardened Bash CLI scripts with getopts option parsing and help menus — entirely on this device.
Script Metadata & Shell Features
CLI Options & Flags (4)
Generated Bash Script
Generated Optstring::hve:t:Do it offline:$
How to use it
- Define script metadata including filename and usage summary.
- Toggle shell robustness options: strict mode (set -euo pipefail) and positional argument shifting.
- Add CLI flags, choosing whether each flag is a boolean switch (-v) or takes a parameter (-f <file>).
- Specify variable names, default values, and mark required arguments for automatic validation.
- Copy the fully scaffolded Bash script, make it executable with chmod +x, and test it with the -h flag.
Scaffold POSIX-compliant, error-hardened Bash CLI scripts using getopts. Features automated optstring generation, silent error reporting, help usage menus, strict mode, and required argument validation.
How it works
The getopts builtin is defined by the POSIX standard and built directly into Bash, Dash, and ksh, requiring no external dependencies.
Prefixing the optstring with a colon (:) activates silent error mode. In silent mode, missing arguments trigger the :) case and invalid flags trigger \?), allowing custom user-friendly error messages.
The OPTARG variable holds the argument value for options requiring parameters. The OPTIND variable tracks index position in the argument list.
Calling shift $((OPTIND - 1)) strips parsed flags from the positional parameter list, leaving only remaining operands ($@ or $1, $2).
Examples
Every example on this page is executed against the same engine that powers the tool, on every build.
Gotchas worth knowing
Common errors
FAQ
What is the difference between getopts and getopt?
getopts is a shell builtin defined by POSIX available in all standard shells. getopt (with no 's') is an external binary (/usr/bin/getopt) from util-linux. Because getopt is an external binary with historical quoting bugs and portability quirks across macOS and BSD, standard scripts recommend getopts.
Can getopts parse long options like --output or --file?
Standard POSIX getopts only supports single-character short options (-f, -o). To handle long options while remaining portable, scripts either map -: to an argument or combine short flags with a manual case statement on $1.
Why should my Bash script use set -euo pipefail?
Bash strict mode prevents silent script errors: -e exits immediately if any command returns a non-zero exit code; -u throws an error if an undefined variable is referenced; and -o pipefail ensures pipeline exit codes reflect the first failing command rather than only the final command.