Getopts Argument Parser With Validation
Parse command line options using bash getopts with validation, default values, and usage messages.
Code
#!/usr/bin/env bash
set -euo pipefail
VERBOSE=0
OUTPUT=""
INPUT=""
usage() {
echo "Usage: $0 [-v] [-o output] -i input" >&2
exit 1
}
while getopts ":vo:i:" opt; do
case "${opt}" in
v) VERBOSE=1 ;;
o) OUTPUT="${OPTARG}" ;;
i) INPUT="${OPTARG}" ;;
\?) echo "Unknown option: -${OPTARG}" >&2; usage ;;
:) echo "Missing argument for -${OPTARG}" >&2; usage ;;
esac
done
[[ -z "${INPUT}" ]] && usage
OUTPUT="${OUTPUT:-output.txt}"
[[ "${VERBOSE}" -eq 1 ]] && echo "Input: ${INPUT}, Output: ${OUTPUT}"What the code does
set -euo pipefail removes the shell’s usual optimism — errors abort, empty variables abort, hidden pipeline failures abort.
A helper function (usage) keeps the repeated logic out of the main flow.
Option parsing walks the argument list explicitly, so flags, their values, and positional arguments are handled in one place.
The script leans on parameter expansion 10 times, using forms like ${var:-default} so defaults, trimming, and casing happen inside the shell with no external tool.
Applying it
The script self-documents: the help branch prints $0 [-v] [-o output] -i 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.
Statements that carry the weight
while getopts ":vo:i:" opt; do
case "${opt}" in
Interactive Tools for This Topic
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.