Once a script has more than two or three inputs, positional arguments get confusing. Was it ./deploy.sh prod checkout 3 or ./deploy.sh checkout 3 prod? Real tools use options: -e prod -r 3 -v checkout. Order stops mattering, defaults are obvious and -h explains everything. Bash's built-in getopts parses short options correctly with a few lines of code.
In simple words
- Option: a flag that changes how the script behaves, such as -v or -f file.
- getopts: Bash's built-in helper for reading short options safely.
- Usage function: prints how to use the script, shown on -h or on a mistake.
- Dry run: a mode that shows what the script would do without changing anything.
Options, values and operands
./deploy.sh -v -e prod -r 3 checkout │ │ │ └── operand (a normal argument) │ │ └── option with a value │ └── option with a value └── flag (an option without a value)Conventions every Unix user expects:
- Short options are a dash and one letter:
-v. - Flags can be combined:
-vfis the same as-v -f. - A value can be attached or separate:
-eprodor-e prod. --ends the options; everything after it is an operand, even if it starts with-.-hprints help.
getopts handles all of these for you.
The getopts loop
#!/usr/bin/env bashverbose=0env=stagingreplicas=2 while getopts ":ve:r:h" opt; do case "$opt" in v) verbose=1 ;; e) env=$OPTARG ;; r) replicas=$OPTARG ;; h) echo "usage: $0 [-v] [-e ENV] [-r N] APP"; exit 0 ;; :) echo "option -$OPTARG needs a value" >&2; exit 2 ;; \?) echo "unknown option -$OPTARG" >&2; exit 2 ;; esacdoneshift $((OPTIND - 1)) app=${1:?usage: $0 [-v] [-e ENV] [-r N] APP}echo "app=$app env=$env replicas=$replicas verbose=$verbose"How it works:
- The option string
":ve:r:h"lists the letters you accept. A letter followed by:takes a value (e:andr:); a letter without one is a flag. - Each call to
getoptsreads the next option, puts its letter in$opt, and returns 0. When there are no more options it returns non-zero and thewhileloop ends. $OPTARGholds the value of options that take one.- The leading
:turns on "silent" error mode, so you print the messages: an unknown option givesopt=?and a missing value givesopt=:, with the offending letter in$OPTARG. Without the leading colon, getopts prints its own generic errors. $OPTINDis the index of the next argument to process. After the loop,shift $((OPTIND - 1))removes all the options, so the operands start at$1again.
Try it
Create the script in the practice terminal and run it with different arguments:
printf '#!/usr/bin/env bash\nverbose=0; env=staging; replicas=2\nwhile getopts ":ve:r:h" opt; do\n case "$opt" in\n v) verbose=1 ;;\n e) env=$OPTARG ;;\n r) replicas=$OPTARG ;;\n h) echo "usage: $0 [-v] [-e ENV] [-r N] APP"; exit 0 ;;\n :) echo "option -$OPTARG needs a value" >&2; exit 2 ;;\n \\?) echo "unknown option -$OPTARG" >&2; exit 2 ;;\n esac\ndone\nshift $((OPTIND - 1))\napp=${1:-}\n[[ -n $app ]] || { echo "missing APP" >&2; exit 2; }\necho "app=$app env=$env replicas=$replicas verbose=$verbose"\n' > deploy.shchmod +x deploy.sh./deploy.sh checkout./deploy.sh -v -e prod -r 4 checkout./deploy.sh -ve prod checkout./deploy.sh -eprod -r3 checkoutapp=checkout env=staging replicas=2 verbose=0app=checkout env=prod replicas=4 verbose=1app=checkout env=prod replicas=2 verbose=1app=checkout env=prod replicas=3 verbose=0All four calls were parsed correctly, including the combined -ve prod and the attached -eprod. Now the error cases:
./deploy.sh -x checkout./deploy.sh -e./deploy.sh -hunknown option -xoption -e needs a valueusage: ./deploy.sh [-v] [-e ENV] [-r N] APPValidating option values
getopts checks the shape of the command line, not the values. Validate those after the loop:
case "$env" in dev|staging|prod) ;; *) echo "invalid -e '$env' (expected dev, staging or prod)" >&2; exit 2 ;;esac if [[ ! $replicas =~ ^[0-9]+$ ]] || (( replicas < 1 || replicas > 20 )); then echo "invalid -r '$replicas' (expected 1-20)" >&2 exit 2fiA proper usage function
Help text is part of the interface. Put it in a function, print it for -h (to stdout, exit 0) and for errors (to stderr, exit 2):
usage() { cat <<EOFUsage: ${0##*/} [options] APPDeploy APP to an environment.Options: -e ENV target environment: dev, staging, prod (default: staging) -r N number of replicas, 1-20 (default: 2) -n dry run: print what would happen -v verbose output -h show this helpExamples: ${0##*/} checkout ${0##*/} -e prod -r 4 checkoutEOF}Then: h) usage; exit 0 ;; and \?) usage >&2; exit 2 ;;.
Repeated options
Some options make sense more than once, like -v -v for more verbosity or -t a -t b for several tags. Count or collect them:
printf '#!/usr/bin/env bash\nlevel=0; tags=()\nwhile getopts "vt:" o; do\n case $o in\n v) level=$((level + 1)) ;;\n t) tags+=("$OPTARG") ;;\n esac\ndone\necho "verbosity=$level tags=${tags[*]}"\n' > multi.shchmod +x multi.sh./multi.sh -vv -t web -t canaryverbosity=2 tags=web canaryWhat getopts does not do: long options
getopts only understands single-letter options. For --env prod or --dry-run, you have three choices:
- Keep to short options. Simple and portable; fine for most internal scripts.
- Write a manual
whileloop withcase, which handles long options and is very readable:
while [[ $# -gt 0 ]]; do case "$1" in -e|--env) env=${2:?--env needs a value}; shift 2 ;; --env=*) env=${1#*=}; shift ;; -n|--dry-run) dry_run=1; shift ;; -v|--verbose) verbose=1; shift ;; -h|--help) usage; exit 0 ;; --) shift; break ;; -*) echo "unknown option $1" >&2; usage >&2; exit 2 ;; *) break ;; esacdone- Use the external
getopt(no "s", from util-linux), which supports long options but behaves differently across systems. Avoid it in portable scripts.
The manual loop is what many popular open-source Bash tools use. Its trade-off is that combined flags like -vn are not split for you.
A dry-run flag
A -n / --dry-run flag that prints commands instead of running them makes any destructive script much safer to use and to review. A tiny helper does it:
dry_run=1run() { if [[ $dry_run == 1 ]]; then echo "+ $*"; else "$@"; fi; }run kubectl scale deploy/checkout --replicas=4 -n prodrun rm -rf /tmp/release-old+ kubectl scale deploy/checkout --replicas=4 -n prod+ rm -rf /tmp/release-oldWrap every command that changes something in run, and reviewers can see exactly what the script will do before it does it.
Real-world scenario: one script, many environments
A platform team had five near-identical scripts, deploy-dev.sh, deploy-staging.sh, deploy-prod.sh and so on, that drifted apart over time. They replaced them with one script:
deploy.sh -e prod -r 4 -t 2.4.1 -n checkout-echose the environment, validated against a list.-rand-tset replicas and image tag, with sensible defaults.-nprinted everykubectlcommand without running it, which became a required step in their change review.-hdocumented everything, so new team members stopped asking how to deploy.
One script meant one place to fix bugs, and -n output pasted into the change ticket made production deploys much easier to approve.
Common mistakes
- Forgetting
shift $((OPTIND - 1)): operands stay mixed with options. - Missing
:after a letter that needs a value:$OPTARGis empty and the value becomes an operand. - Putting operands before options:
getoptsstops at the first non-option, so./deploy.sh checkout -e prodignores-e prod. Document "options first". - Forgetting
\?in thecase(the?must be escaped or quoted, or it matches any single character). - Not resetting
OPTIND=1when using getopts inside a function that is called more than once. - Expecting long options from getopts.
Practice
- Write
backup.shthat accepts-s SOURCE,-d DEST,-k DAYS(default 7) and-nfor dry run, then prints the settings. - Make it fail with a clear message when
-sor-dis missing. - Add a
usagefunction with a here-document and wire it to-hand to errors. - Validate that
-kis a positive number. - Rewrite the parsing with a manual
while/caseloop that also accepts--source,--destand--dry-run.
Cheat sheet
while getopts ":ab:c:h" opt; do a = flag, b: and c: take values case $opt in a) … ;; b) val=$OPTARG ;; h) usage; exit 0 ;; :) echo "-$OPTARG needs a value" >&2; exit 2 ;; \?) echo "unknown -$OPTARG" >&2; exit 2 ;; esacdoneshift $((OPTIND - 1)) operands now start at $1OPTIND=1 reset before reusing getoptscase $1 in --long=*) v=${1#*=} ;; esac manual long optionsrun() { [[ $dry_run == 1 ]] && echo "+ $*" || "$@"; }Key takeaways
- Options make scripts self-explanatory and order-independent;
getoptsparses short options, combined flags and attached values. - The option string lists letters, with
:after those that take a value; a leading:lets you print your own errors. - Always
shift $((OPTIND - 1))after the loop, then validate values separately. - Provide
-hwith a clear usage text, and a-ndry-run mode for anything destructive. - For long options, write a manual
while/caseloop.