Bash Getopts Subcommand Parsing
Parse CLI subcommands and options with getopts for shell script tooling.
Code
#!/bin/bash
subcommand="$1"; shift
case "$subcommand" in
serve)
port=8080
while getopts ":p:" opt; do
case "$opt" in
p) port="$OPTARG" ;;
\?) echo "unknown: -$OPTARG" >&2; exit 1 ;;
esac
done
echo "serving on port $port"
;;
build)
output="dist"
while getopts ":o:" opt; do
case "$opt" in o) output="$OPTARG" ;; esac
done
echo "building to $output"
;;
*) echo "usage: $0 {serve|build}" >&2; exit 1 ;;
esacHow the snippet works
Option parsing walks the argument list explicitly, so flags, their values, and positional arguments are handled in one place.
Applying it
The script self-documents: the help branch prints $0 {serve|build}.
Flags are consumed by the option loop and positional arguments are read after it, so script -v -o out input and script input both behave predictably.
Statements that matter most here
while getopts ":p:" opt; do
case "$opt" in
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
Report a problem with this exampleOpens a pre-filled issue on GitHub.