Anatomy of a Production Script
A one-off command line becomes a script the moment someone else runs it, or you run it twice. From then on it needs the things any program needs: a clear interface, predictable failure, and a way to tell the caller what happened. This lesson builds a template you can start every Bash script from; the rest of the Robust Bash section explains each part in depth.
The template
#!/usr/bin/env bash
# backup-config: copy a config directory into a dated archive folder.
# Usage: backup-config [-n] SOURCE_DIR DEST_DIR
set -euo pipefail
readonly PROG=${0##*/}
DRY_RUN=0
log() { printf '%s: %s\n' "$PROG" "$*" >&2; }
die() { log "error: $*"; exit 1; }
usage() {
cat <<USAGE
Usage: $PROG [-n] SOURCE_DIR DEST_DIR
-n dry run: print what would be copied, change nothing
USAGE
}
main() {
while getopts ':nh' opt; do
case $opt in
n) DRY_RUN=1 ;;
h) usage; exit 0 ;;
*) usage >&2; exit 2 ;;
esac
done
shift $((OPTIND - 1))
[ $# -eq 2 ] || { usage >&2; exit 2; }
local src=$1 dest=$2
[ -d "$src" ] || die "no such directory: $src"
...
}
main "$@"Each line earns its place:
| Part | Why |
|---|---|
#!/usr/bin/env bash |
runs Bash wherever it is installed; #!/bin/sh would give you dash on Debian and Ubuntu, without arrays or [[ ]] |
| a header comment with usage | the first thing the next person reads; --help repeats it |
set -euo pipefail |
stop on errors, unset variables and failed pipelines (Strict Mode and Its Traps) |
readonly PROG=${0##*/} |
the script's own name for messages, without the directory |
log writes to stderr |
stdout is for data the caller may pipe or capture; messages must not pollute it |
die |
one way to fail: a message and a non-zero status |
usage and exit status 2 |
the convention for "you called me wrong", distinct from 1, "I tried and failed" |
everything inside main |
variables can be local, and the file is parsed completely before anything runs |
main "$@" as the last line |
passes every argument through unchanged, with spaces intact |
The last point is subtle. Bash reads a script as it executes it. If someone edits or replaces the file while a long run is in progress, Bash can continue reading at the old byte offset in the new content. When the whole program is a function called on the last line, Bash has already read every function body before it runs anything.
The template, running
Here is a complete small script built from the template. The session creates it, then calls it the ways a real user
or a CI job would: without arguments, with -h, with a bad option, with a missing directory, as a dry run and for real.
cat > backup-config <<'SCRIPT'
#!/usr/bin/env bash
# backup-config: copy a config directory into DEST_DIR/<name>.bak
set -euo pipefail
readonly PROG=${0##*/}
DRY_RUN=0
log() { printf '%s: %s\n' "$PROG" "$*" >&2; }
die() { log "error: $*"; exit 1; }
usage() { echo "Usage: $PROG [-n] SOURCE_DIR DEST_DIR"; }
main() {
while getopts ':nh' opt; do
case $opt in
n) DRY_RUN=1 ;;
h) usage; exit 0 ;;
*) log "unknown option: -$OPTARG"; usage >&2; exit 2 ;;
esac
done
shift $((OPTIND - 1))
[ $# -eq 2 ] || { usage >&2; exit 2; }
local src=$1 dest=$2
[ -d "$src" ] || die "no such directory: $src"
local target
target="$dest/$(basename "$src").bak"
if [ "$DRY_RUN" -eq 1 ]; then
log "dry run: would copy $src to $target"
return 0
fi
mkdir -p "$dest"
cp -R "$src" "$target"
log "copied $(find "$target" -type f | wc -l) file(s) to $target"
}
main "$@"
SCRIPT
chmod +x backup-config
mkdir -p etc/app && echo "port=8080" > etc/app/app.conf && echo "debug=false" > etc/app/log.conf
./backup-config; echo "-> status $?"
./backup-config -h; echo "-> status $?"
./backup-config -x etc/app b; echo "-> status $?"
./backup-config etc/nope b; echo "-> status $?"
./backup-config -n etc/app backups; echo "-> status $?"
./backup-config etc/app backups; echo "-> status $?"
ls backups/app.bakUsage: backup-config [-n] SOURCE_DIR DEST_DIR
-> status 2
Usage: backup-config [-n] SOURCE_DIR DEST_DIR
-> status 0
backup-config: unknown option: -x
Usage: backup-config [-n] SOURCE_DIR DEST_DIR
-> status 2
backup-config: error: no such directory: etc/nope
-> status 1
backup-config: dry run: would copy etc/app to backups/app.bak
-> status 0
backup-config: copied 2 file(s) to backups/app.bak
-> status 0
app.conf
log.conf
Notice what the caller gets: usage errors exit with 2, a real failure with 1, success with 0, and every message goes to stderr (in this session stderr and stdout are shown together). A CI step or a cron wrapper can act on those numbers without parsing any text.
What the template leaves out on purpose
- Cleanup. This script creates nothing temporary. As soon as one does, it needs a
trap(trap: Cleanup, Signals and Exit Status). - Long options.
getoptsonly handles single-letter options. Arguments, Usage and Exit Codes shows a small loop that parses--dry-runstyle options too. - Running twice. Run the last command again and
cp -Rcopies the directory into the existingapp.bak, makingapp.bak/app. Idempotent Scripts is about scripts that give the same result however often they run. IFS=#39;\n\t'. Some templates also changeIFSso unquoted variables split only on newlines and tabs. It hides missing quotes instead of fixing them; quote your variables and let ShellCheck find the ones you missed.
Test yourself
Why does the template send log messages to stderr?
- stderr is faster
- So stdout stays clean for data that callers capture or pipe
- Because
printfcannot write to stdout - stderr is never shown to users
What exit status does the template use when the script is called with the wrong arguments?
- 0
- 1
- 2
- 127
What is the benefit of putting the logic in main and calling main "$@" on the last line?
- It makes the script run faster
- Bash has parsed every function before anything runs, variables can be local, and all arguments pass through intact
- It is required by
set -e - It disables globbing