Functions, Arguments and Parsing Options: $@, shift, getopts and a Good --help
A Bash function returns data on stdout and success through its exit code; variables inside it are global unless declared local, and scope is dynamic. We collect shared functions in a sourced library and use positional parameters, shift, getopts and a while/case pattern for long options to build Bookstore's bookstore-deploy.sh -e staging -v 1.4.2 --dry-run interface, a good --help text and a dry run based on printf %q.
Version note: The examples in this post were run on Ubuntu 24.04 LTS with Bash 5.2.21 and Bash 5.3.20 built from source, using ShellCheck 0.11.0.
Guess First
A function builds a health URL from an environment name. The script calls it twice and finally prints its own url variable:
#!/usr/bin/env bash
health_url() {
url="https://$1.bookstore.test/health"
echo "$url"
}
url=http://127.0.0.1:5000/health
staging_url=$(health_url staging)
health_url production > /dev/null
echo "staging: $staging_url"
echo "caller's url: $url"
What does the last line print: 127.0.0.1, staging or production? The only difference between the two calls is that one is inside $(...). The answer is in the local section.
In the previous post our scripts learned to make decisions, but they still pick arguments apart by hand: the cleanup script only looks for -n in the first argument. In this post we look at functions, local and scope, collecting functions in a library and sharing them with source, positional parameters, shift and getopts. By the end Bookstore has a bookstore-deploy.sh -e staging -v 1.4.2 --dry-run interface with the right error codes and a good --help text.
Defining Functions, Arguments and Return Values
In Bash, a function is a named group of commands. It is called like a command, receives its arguments as $1, $2, "$@", and returns an exit code like a command. There are two ways to "return" something, and they serve different purposes:
# Prints the name of the release that ROOT/current points to.
# Usage: current_release [ROOT]; returns 1 when there is no current release.
current_release() {
local root="${1:-${BOOKSTORE_ROOT:-/opt/bookstore}}"
local target
target=$(readlink -f "$root/current") || return 1
[[ -d $target ]] || return 1
echo "${target##*/}"
}
$ release=$(current_release) && echo "release=$release"
release=1.4.2
$ current_release /tmp/empty || echo "no release, status=$?"
no release, status=1
Data comes from stdout and is captured with $(...); success or failure comes from the exit code and is given with return. return is only a status code between 0 and 255; it is not a way to hand back a number or a string. Without a return, the function ends with the exit code of its last command; the last line above is an echo, so a successful call returns 0. The rule that keeps the two channels apart: write only data to a function's stdout and send messages to stderr. From this post on, release names are version numbers (1.4.2) instead of the names in the previous post; sort -V sorts them correctly too.
local, Scope and Global Variables
The answer to Guess First:
$ ./scope.sh
staging: https://staging.bookstore.test/health
caller's url: https://production.bookstore.test/health
In Bash, a variable assigned inside a function is global unless it is declared with local. The call health_url production overwrote the caller's url. $(health_url staging) did not, because command substitution runs in a separate subshell and the assignment there disappears with it. The same function behaves differently depending on how it is called; the PATH overwrite from the second post happens inside functions in the same way. The fix is to make every variable inside a function local; the Google Shell Style Guide asks for this too.
local has one more subtlety: bash scope is dynamic. A function's local variable is also visible to the functions it calls:
$ cat dynamic.sh
#!/usr/bin/env bash
show() { echo "show sees: $name"; }
outer() {
local name=inner
show
}
name=global
outer
show
$ ./dynamic.sh
show sees: inner
show sees: global
In C#, a method's local variable belongs only to that method; in bash, show sees the name of outer when it is called from outer. So pass data to functions as arguments, not through globals or the caller's locals. There are places where you use globals on purpose: the ENV_NAME, VERSION and DRY_RUN that parse_args fills in the deploy script. Naming them in upper case and declaring them at the top of the script is the way to say "these are global on purpose".
A Function Library: Sharing with source
Writing logs, failing with an error and the dry run are needed in more than one script. We collect them in scripts/lib/common.sh and source it in every script. Following the Google Shell Style Guide, the library file has a .sh extension and is not executable:
# shellcheck shell=bash
#
# common.sh - shared functions for the Bookstore ops scripts.
# Source it from a script; do not run it directly.
if [[ ${BASH_SOURCE[0]} == "$0" ]]; then
echo "${0##*/} is a library; source it from a script instead of running it" >&2
exit 2
fi
# Writes a timestamped message to stderr, so stdout stays free for data.
log() {
printf '%s %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$*" >&2
}
# Logs an error and exits. Usage: die MESSAGE [EXIT_CODE]
die() {
log "ERROR: $1"
exit "${2:-1}"
}
# Runs a command, or only prints it (shell-quoted) when DRY_RUN is 1.
run() {
if (( ${DRY_RUN:-0} )); then
printf '[dry-run]'
printf ' %q' "$@"
printf '\n'
return 0
fi
"$@"
}
# Prints the name of the release that ROOT/current points to.
# Usage: current_release [ROOT]; returns 1 when there is no current release.
current_release() {
local root="${1:-${BOOKSTORE_ROOT:-/opt/bookstore}}"
local target
target=$(readlink -f "$root/current") || return 1
[[ -d $target ]] || return 1
echo "${target##*/}"
}
The # shellcheck shell=bash on the first line tells ShellCheck which shell a file without a shebang is written for. BASH_SOURCE[0] is the name of the file currently running and $0 the name of the script that was started; if they are equal, the file was run directly instead of being sourced. Scripts load the library through the SCRIPT_DIR from the previous post; the status command of bookstore-ctl.sh now uses current_release and die:
SCRIPT_DIR=$(dirname "$(readlink -f "$0")")
# shellcheck source=lib/common.sh
source "$SCRIPT_DIR/lib/common.sh"
$ ./scripts/bookstore-ctl.sh status
current release: 1.4.2
OK http://127.0.0.1:5000/health
$ BOOKSTORE_ROOT=/tmp/empty ./scripts/bookstore-ctl.sh status; echo "exit=$?"
2026-11-15T03:54:48Z ERROR: no current release under /tmp/empty
exit=1
$ bash scripts/lib/common.sh; echo "exit=$?"
common.sh is a library; source it from a script instead of running it
exit=2
By default ShellCheck does not follow a sourced file. As soon as the library was added, two warnings came up:
$ shellcheck scripts/*.sh scripts/lib/*.sh && echo "shellcheck: clean"
In scripts/bookstore-deploy.sh line 10:
source "$SCRIPT_DIR/lib/common.sh"
^-------------------------^ SC1091 (info): Not following: lib/common.sh was not specified as input (see shellcheck -x).
In scripts/bookstore-deploy.sh line 71:
DRY_RUN=1
^-----^ SC2034 (warning): DRY_RUN appears unused. Verify use (or export if used externally).
The second warning follows from the first: ShellCheck cannot see inside run, so it takes DRY_RUN for an unused variable. A .shellcheckrc at the repository root makes both go away:
# Follow "source" lines, resolving their paths relative to the script that sources them
external-sources=true
source-path=SCRIPTDIR
$ shellcheck scripts/*.sh scripts/lib/*.sh && echo "shellcheck: clean"
shellcheck: clean
Positional Parameters and shift
The arguments passed to a script (or a function) are numbered $1, $2 and so on, and $# is their count. Beyond nine you need braces: ${10}. shift N moves the list N places to the left:
$ set -- -e staging -v 1.4.2 --dry-run
$ echo "$# args: first=$1 second=$2 all=[$*]"
5 args: first=-e second=staging all=[-e staging -v 1.4.2 --dry-run]
$ shift 2; echo "$# left: $*"
3 left: -v 1.4.2 --dry-run
$ shift 5; echo "shift status=$?, still $# left"
shift status=1, still 3 left
A shift that tries to move more than what is left does nothing and returns 1. That is why every loop that parses options must check that there are enough arguments before it shifts; otherwise it loops forever over the same argument.
Short Options with getopts
getopts is bash's builtin option parser. It only knows single-letter options, but it gives you combined flags (-nv 1.4.2) and missing-value checks for free:
#!/usr/bin/env bash
# Short options only, parsed with getopts
env_name="" version="" dry_run=0
while getopts ":e:v:nh" opt; do
case $opt in
e) env_name=$OPTARG ;;
v) version=$OPTARG ;;
n) dry_run=1 ;;
h) echo "Usage: ${0##*/} -e ENV -v VERSION [-n]"; exit 0 ;;
:) echo "option -$OPTARG needs a value" >&2; exit 2 ;;
\?) echo "unknown option: -$OPTARG" >&2; exit 2 ;;
esac
done
shift $((OPTIND - 1))
echo "env=$env_name version=$version dry_run=$dry_run rest=[$*]"
$ ./getopts-demo.sh -e staging -v 1.4.2 -n
env=staging version=1.4.2 dry_run=1 rest=[]
$ ./getopts-demo.sh -nv 1.4.2 -e staging
env=staging version=1.4.2 dry_run=1 rest=[]
$ ./getopts-demo.sh -e staging extra -n
env=staging version= dry_run=0 rest=[extra -n]
$ ./getopts-demo.sh -e; echo "exit=$?"
option -e needs a value
exit=2
$ ./getopts-demo.sh -x; echo "exit=$?"
unknown option: -x
exit=2
$ ./getopts-demo.sh -e staging --dry-run; echo "exit=$?"
unknown option: --
exit=2
In the option string ":e:v:nh", a : after a letter means "this option takes a value"; the leading : lets you write the error messages instead of getopts: on a missing value opt becomes :, on an unknown option ?, and in both cases the option letter is in OPTARG. OPTIND is the number of the next argument; after the loop, shift $((OPTIND - 1)) drops the options and leaves the rest in $@. getopts stops at the first argument that is not an option: the -n after extra was never processed. The last example shows getopts' limit: it does not know --dry-run and takes the second dash after the first as an option letter.
Long Options: the while/case Pattern and a Good --help
For long options (--env staging, --env=staging), the most portable way is to read the arguments yourself in a while loop with case. The getopt on Linux (without the s, from util-linux) supports long options, but the BSD version on macOS does not; a hand-written loop works the same everywhere. Bookstore's deploy script:
#!/usr/bin/env bash
#
# bookstore-deploy.sh - deploys a Bookstore API release on this server.
#
# Run with --help for options.
# Exit codes: 0 success, 1 deploy failed, 2 usage error
SCRIPT_DIR=$(dirname "$(readlink -f "$0")")
# shellcheck source=lib/common.sh
source "$SCRIPT_DIR/lib/common.sh"
ROOT="${BOOKSTORE_ROOT:-/opt/bookstore}"
ARTIFACT_DIR="${ARTIFACT_DIR:-/var/tmp/bookstore}"
SERVICE="bookstore-api"
# Set by parse_args
ENV_NAME=""
VERSION=""
DRY_RUN=0
usage() {
cat <<EOF_USAGE
Usage: ${0##*/} -e ENV -v VERSION [-n] [-h]
Deploys a Bookstore API release on this server.
Options:
-e, --env ENV target environment: staging or production
-v, --version VERSION release to deploy, for example 1.4.2
-n, --dry-run print the commands instead of running them
-h, --help show this help and exit
Environment:
BOOKSTORE_ROOT installation root (default /opt/bookstore)
ARTIFACT_DIR folder with bookstore-api-VERSION-linux-x64.tar.gz
(default /var/tmp/bookstore)
Example:
${0##*/} -e staging -v 1.4.2 --dry-run
EOF_USAGE
}
usage_error() {
echo "${0##*/}: $1" >&2
echo "Try '${0##*/} --help' for more information." >&2
exit 2
}
parse_args() {
while (( $# > 0 )); do
case $1 in
-e | --env)
(( $# >= 2 )) || usage_error "option $1 needs a value"
ENV_NAME=$2
shift 2
;;
--env=*)
ENV_NAME=${1#*=}
shift
;;
-v | --version)
(( $# >= 2 )) || usage_error "option $1 needs a value"
VERSION=$2
shift 2
;;
--version=*)
VERSION=${1#*=}
shift
;;
-n | --dry-run)
DRY_RUN=1
shift
;;
-h | --help)
usage
exit 0
;;
--)
shift
break
;;
-*)
usage_error "unknown option: $1"
;;
*)
usage_error "unexpected argument: $1"
;;
esac
done
(( $# == 0 )) || usage_error "unexpected argument: $1"
}
validate_args() {
case $ENV_NAME in
staging | production) ;;
"") usage_error "missing -e ENV" ;;
*) usage_error "unknown environment: $ENV_NAME (use staging or production)" ;;
esac
[[ -n $VERSION ]] || usage_error "missing -v VERSION"
[[ $VERSION =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || usage_error "VERSION must look like 1.4.2, got: $VERSION"
}
deploy() {
local artifact="$ARTIFACT_DIR/bookstore-api-$VERSION-linux-x64.tar.gz"
local release_dir="$ROOT/releases/$VERSION"
[[ -f $artifact ]] || die "artifact not found: $artifact"
[[ ! -e $release_dir ]] || die "release $VERSION already exists: $release_dir"
log "deploying $VERSION to $ENV_NAME"
run mkdir -p "$release_dir"
run tar -xzf "$artifact" -C "$release_dir"
run ln -sfn "$release_dir" "$ROOT/current"
run sudo systemctl restart "$SERVICE"
run "$SCRIPT_DIR/bookstore-health.sh" local || die "health check failed after deploying $VERSION"
if (( DRY_RUN )); then
log "dry run finished, nothing was changed"
else
log "deployed $VERSION"
fi
}
main() {
parse_args "$@"
validate_args
deploy
}
main "$@"; exit
The structure has three steps: parse_args only reads, validate_args checks that the values make sense, deploy does the work. Every usage mistake goes through usage_error: the message to stderr, then a pointer to --help, then 2. The cat <<EOF_USAGE in usage is a here-doc: it feeds the text from the following lines up to the end marker to stdin, and expansions such as ${0##*/} work in it; the details are in the fifth post. A help text should contain four things: a one-line usage, what the script does, a description of every option, and an example that can be copied and run. --help writes to stdout and ends with 0; the message for incorrect usage goes to stderr and ends with 2.
$ ./scripts/bookstore-deploy.sh -e qa -v 1.4.2; echo "exit=$?"
bookstore-deploy.sh: unknown environment: qa (use staging or production)
Try 'bookstore-deploy.sh --help' for more information.
exit=2
$ ./scripts/bookstore-deploy.sh --env=staging -v 1.4; echo "exit=$?"
bookstore-deploy.sh: VERSION must look like 1.4.2, got: 1.4
Try 'bookstore-deploy.sh --help' for more information.
exit=2
$ ./scripts/bookstore-deploy.sh -e staging -v; echo "exit=$?"
bookstore-deploy.sh: option -v needs a value
Try 'bookstore-deploy.sh --help' for more information.
exit=2
$ ./scripts/bookstore-deploy.sh -e staging -v 1.4.2 --force; echo "exit=$?"
bookstore-deploy.sh: unknown option: --force
Try 'bookstore-deploy.sh --help' for more information.
exit=2
Compared with getopts, this pattern lacks one thing: it does not split combined short options such as -nv 1.4.2. For a script like deploy, which runs rarely and where readability matters, that is an acceptable price.
--dry-run: Showing Dangerous Commands First
Every command in deploy that changes something goes through run. When DRY_RUN=1, run does not run the command; it quotes it with printf %q in a form that can be pasted into a shell and prints it:
$ ./scripts/bookstore-deploy.sh -e staging -v 1.4.2 --dry-run
2026-11-15T03:54:14Z deploying 1.4.2 to staging
[dry-run] mkdir -p /opt/bookstore/releases/1.4.2
[dry-run] tar -xzf /var/tmp/bookstore/bookstore-api-1.4.2-linux-x64.tar.gz -C /opt/bookstore/releases/1.4.2
[dry-run] ln -sfn /opt/bookstore/releases/1.4.2 /opt/bookstore/current
[dry-run] sudo systemctl restart bookstore-api
[dry-run] /home/user/bookstore-ops/scripts/bookstore-health.sh local
2026-11-15T03:54:14Z dry run finished, nothing was changed
$ ls /opt/bookstore/releases
1.4.0
1.4.1
$ DRY_RUN=1 run rm -rf "/opt/bookstore/releases/1.4.0 old" '$HOME'
[dry-run] rm -rf /opt/bookstore/releases/1.4.0\ old \$HOME
Thanks to %q, a path with a space or an argument containing $ appears exactly as it would run; with echo "$@" you could not tell from the output whether 1.4.0 old is one argument or two. The dry run still checks the preconditions: if the artifact is missing, the dry run fails too, which narrows the gap between "the dry run was clean" and "the real deploy blew up".
Now a real deploy. The lab container has no systemd, so sudo and systemctl are two small stubs that I put at the front of the PATH and that say what they do; every other step is real:
$ PATH="$HOME/lab-stubs:$PATH" ./scripts/bookstore-ctl.sh deploy -e staging -v 1.4.2
2026-11-15T03:54:14Z deploying 1.4.2 to staging
(lab stub) systemctl restart bookstore-api
OK http://127.0.0.1:5000/health
2026-11-15T03:54:14Z deployed 1.4.2
$ ./scripts/bookstore-ctl.sh releases
1.4.0
1.4.1
* 1.4.2
$ PATH="$HOME/lab-stubs:$PATH" ./scripts/bookstore-deploy.sh -e staging -v 1.4.2; echo "exit=$?"
2026-11-15T03:54:14Z ERROR: release 1.4.2 already exists: /opt/bookstore/releases/1.4.2
exit=1
The new deploy) branch in bookstore-ctl.sh passes the arguments on to the deploy script unchanged with "$@". Deploying the same version a second time is refused; how to undo a deploy that stops halfway, and why ln -sfn on its own is not safe enough, are the topics of the sixth and seventh posts.
In Production
Think of the script's interface as an API: CI pipelines, runbooks and your teammates will call it. Changing option names and exit codes breaks every caller. Adding a new option is safe; changing the meaning of an existing one is not. If you have to, accept the old name for a while and print a warning to stderr.
Consider an extra confirmation for production. When -e production is given and the terminal is interactive ([[ -t 0 ]]), a question such as "type the version number to continue" stops a command run in the wrong tab; in CI, an explicit --yes option is required instead. Do not take secrets as options; as we saw in the second post, arguments are visible in the output of ps. Keep deploy logs timestamped so that they show who deployed which version and when; that is why the log function writes UTC in ISO 8601 format.
Keep the library small. common.sh is loaded by every script; it should hold only functions that are really shared, not business logic. When the library changes, run every script that uses it through ShellCheck; in the last post of the series we also cover it with bats-core tests.
Common Pitfalls
Trying to return a number with return. return reduces the value to 8 bits and fails on a value that is not a number:
$ ./ret.sh
return 300 -> 44
return 256 -> 0
./ret.sh: line 4: return: many: numeric argument required
return many -> 2
A function that returns the number of failed deploys with return says "success" after 256 failures. Print the number with echo and use return for the status.
local x=$(command) hides the exit code. local is a command itself and returns its own exit code (0); the result of the command substitution is lost:
$ ./mask.sh
local target=$(...): status 0
separate assignment: status 1
$ shellcheck -f gcc mask.sh
mask.sh:3:11: warning: target appears unused. Verify use (or export if used externally). [SC2034]
mask.sh:3:11: warning: Declare and assign separately to avoid masking return values. [SC2155]
mask.sh:6:5: warning: other appears unused. Verify use (or export if used externally). [SC2034]
That is why current_release in the library writes local target and target=$(...) on two separate lines. In the sixth post we see that set -e does not notice the error on that line either.
die in a function called from $(...). exit only ends the subshell it runs in:
$ source scripts/lib/common.sh
$ artifact_path() { [[ -f /var/tmp/bookstore/bookstore-api-$1-linux-x64.tar.gz ]] || die "no artifact for $1"; echo "/var/tmp/bookstore/bookstore-api-$1-linux-x64.tar.gz"; }
$ path=$(artifact_path 9.9.9); echo "still running, path=[$path]"
2026-11-15T03:55:13Z ERROR: no artifact for 9.9.9
still running, path=[]
The error message was printed, but the script went on with an empty path. Call functions that return a value as path=$(artifact_path "$v") || die ...; let the caller decide.
Expecting long options from getopts. As we saw above, it reports --dry-run as an unknown - option. If you need long options, choose the while/case pattern from the start; mixing the two in one script makes it hard to follow which option is handled where.
A Small Experiment
★☆☆ Add a -q, --quiet option to bookstore-deploy.sh: when given, it suppresses the log messages but not the error messages (die). Update the --help text as well and check the output of --quiet --dry-run.
★★☆ Add a confirmation for -e production to the deploy script: if stdin is a terminal ([[ -t 0 ]]), ask the user to type the version number again and exit with 1 if it does not match; if it is not a terminal, exit with 2 unless --yes is given. Why should echo 1.4.3 | ./scripts/bookstore-deploy.sh -e production -v 1.4.3 be refused without asking?
★★★ Rewrite bookstore-prune-releases.sh with the new library: its options become -n, --dry-run and -k, --keep N, deletion goes through run, and the current release is found with current_release. Show that bookstore-ctl.sh prune --keep 2 --dry-run passes the arguments on correctly.
The deploy script now has a clean interface, but logs, data and error messages all flow to the same terminal, and exit codes get lost in data that passes through pipes. In the next post we move on to data flow inside scripts: keeping stdout clean for data, writing all output to a log file as well with exec and tee, PIPESTATUS and pipefail, the fix for the counter lost by the while loop, here-docs and parallelism with xargs.