snippetbashModeratepending
Bash argument parsing with getopts — CLI script pattern
Viewed 0 times
getoptsargument parsingflagsoptionsCLIbash script
terminallinuxmacos
Problem
Bash scripts need to accept flags and arguments like -v for verbose, -o outfile, or --help. Parsing $1, $2 manually is fragile and does not handle combined flags like -vf.
Solution
Use getopts for short options. For long options, use a manual case-based parser or switch to Python/argparse for complex CLIs.
Code Snippets
getopts argument parsing template
#!/usr/bin/env bash
set -euo pipefail
VERBOSE=false
OUTPUT=""
DRY_RUN=false
usage() {
echo "Usage: $0 [-v] [-o output] [-n] <input>"
echo " -v Verbose output"
echo " -o Output file (default: stdout)"
echo " -n Dry run"
exit 1
}
while getopts ':vo:nh' opt; do
case $opt in
v) VERBOSE=true ;;
o) OUTPUT="$OPTARG" ;;
n) DRY_RUN=true ;;
h) usage ;;
:) echo "Option -$OPTARG requires an argument" >&2; exit 1 ;;
?) echo "Unknown option -$OPTARG" >&2; usage ;;
esac
done
shift $((OPTIND - 1))
[[ $# -eq 0 ]] && { echo "Error: input required" >&2; usage; }
INPUT="$1"
$VERBOSE && echo "Processing $INPUT..."Revisions (0)
No revisions yet.