Parse Options With getopts
Parse short options and their arguments with getopts so a shell script exposes a predictable CLI instead of positional guesswork.
Code
#!/usr/bin/env bash
set -euo pipefail
verbose=false
output=""
level=1
while getopts ":vo:l:h" opt; do
case "${opt}" in
v) verbose=true ;;
o) output="${OPTARG}" ;;
l)
level="${OPTARG}"
if ! [[ "${level}" =~ ^[1-9]$ ]]; then
echo "level must be 1-9" >&2
exit 2
fi
;;
h)
echo "usage: $0 [-v] [-o output] [-l level] input"
exit 0
;;
:)
echo "option -${OPTARG} requires an argument" >&2
exit 2
;;
\?)
echo "unknown option: -${OPTARG}" >&2
exit 2
;;
esac
done
shift $((OPTIND - 1))
input="${1:?input file is required}"How it works
set -euo pipefail puts the script into strict mode: it stops on the first failing command, treats unset variables as errors, and fails a pipeline if any stage fails.
Option parsing walks the argument list explicitly, so flags, their values, and positional arguments are handled in one place.
Using it
The script self-documents: the help branch prints $0 [-v] [-o output] [-l level] input.
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.
The key statements, annotated
while getopts ":vo:l:h" opt; do
case "${opt}" in
shift $((OPTIND - 1))
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.
FAQ
- Does the script stop on the first error?
- Yes — `set -euo pipefail` aborts on the first failing command, treats unset variables as errors, and fails the whole pipeline if any stage fails. Nothing continues half-broken.
Report a problem with this exampleOpens a pre-filled issue on GitHub.