The Analogy: The Automatic Car Wash Tunnel
Picture an automatic car wash tunnel at a filling station. A car is pulled onto the track, the attendant presses one button, and the car rolls through a fixed, ordered sequence of stations: pre-soak, soap, spinning brushes, high-pressure rinse, wax, and blow-dry. Nobody stands inside scrubbing; the whole procedure is encoded once into the machinery and then runs unattended, the same way, on every car. That is exactly what an automation script is -- a procedure you write down once so the machine can perform it identically every time, without a human repeating the steps by hand.
The tunnel runs off a small control panel. Toggle switches choose wash-only or wash-plus-wax, whether to run the underbody jets, how many rinse passes to make. The operator sets those once and the tunnel behaves accordingly for that car. A good automation script has the same separation: a block of configuration near the top -- variables, defaults, and the arguments the caller passed -- kept apart from the fixed sequence of steps below it, so you can change behaviour by flipping a setting rather than rewiring the machinery.
The tunnel is also built so that running it twice does no harm. Send an already-clean car through again and it comes out clean; nothing breaks, nothing is double-charged in a way that ruins the paint. This property is idempotency: performing the operation a second time leaves you in the same correct state as performing it once. Automation scripts are run on schedules, retried after failures, and fired off by nervous operators who click twice, so a step that is safe to repeat -- create the directory only if absent, add the line only if missing -- is the difference between a robust tool and a landmine.
The failure that defines the tunnel is what happens when a station jams and there is no interlock. If the soap arm seizes but the track keeps moving, the car rolls out the far end looking finished but still dirty, and the next car piles into the jam. A good tunnel has interlocks that halt the whole line the instant a station fails, so a half-washed car never leaves. A script without set -euo pipefail and without checking each step's status is a tunnel with no interlocks: an early command fails, the script sails on regardless, and it reports a clean success over a job that was only half done. Everything downstream then trusts a result that was never true.
Syntax or Core Structure
A robust automation script has a recognisable skeleton: a strict-mode preamble that turns silent failures into hard stops, the work organised into a main function, and a single call to main at the very bottom that passes the script's arguments through:
#!/usr/bin/env bash
set -euo pipefail
main() {
echo "step 1: check"
echo "step 2: act"
echo "step 3: report"
}
main "$@"
Output:
step 1: check
step 2: act
step 3: report
Wrapping the work in main and calling it last is not ceremony. It means the whole script is parsed before any of it runs, so a syntax error near the bottom cannot strike after the top half has already changed your system. It gives every step a named home and a clear order. And main "$@" forwards the caller's arguments into the function unchanged, so the code that reads $1 and $2 lives inside main alongside the logic that uses them, rather than floating loose at the top of the file.
Technical Depth: Strict Mode, Idempotency and Configuration
The strict-mode preamble
Three switches, conventionally written together as set -euo pipefail, are the interlocks that stop a script the moment something goes wrong instead of letting it run on over a broken step:
| Switch | What it does |
|---|---|
set -e | Exit immediately if any command returns a non-zero status |
set -u | Treat use of an unset variable as an error, not an empty string |
set -o pipefail | Make a pipeline fail if any stage in it fails, not just the last |
| combined | set -euo pipefail turns silent, ignored failures into hard stops |
Without -e, a failed mkdir or cd is ignored and the next command runs in the wrong place. Without -u, a typo in a variable name expands to nothing and a path like "$DEST/$naem" quietly becomes "$DEST/". Without pipefail, a pipeline reports the exit status of only its last command, so generate | tee log looks successful even when generate crashed. The most infamous version of the -u trap is rm -rf "$PREFIX/" where PREFIX was never set: with -u the script aborts safely, and without it the command expands to rm -rf /. Turning these three switches on costs one line and removes an entire category of silent, destructive bugs.
set -e and pipefail in action
The effect is easiest to see on a one-liner. Under -e, execution stops at the first failure:
bash -ec 'echo one; false; echo two'; echo "exit=$?"
Output:
one
exit=1
echo one runs, false returns non-zero, and -e halts the script before echo two -- the exit status is the failing command's. Pipefail changes what a pipeline reports:
bash -c 'false | cat; echo "no pipefail: $?"'
bash -c 'set -o pipefail; false | cat; echo "with pipefail: $?"'
Output:
no pipefail: 0
with pipefail: 1
By default the pipeline's status is cat's success, hiding the failure of false; with pipefail the pipeline reports the failure. In an automation script that pipes one stage into another, that difference decides whether a crashed producer is caught or ignored.
Composing main from step functions
As a procedure grows, keep each step a small named function and let main sequence them. Under set -e, if any step returns non-zero the run stops there, so the order in main also encodes the dependency order:
check() { echo "check: inputs present"; }
build() { echo "build: artifact created"; }
report() { echo "report: done"; }
main() {
check
build
report
}
main "$@"
Output:
check: inputs present
build: artifact created
report: done
Each function does one thing and can be read, tested, or reordered on its own, while main stays a short, readable table of contents for the whole procedure. This is the tunnel's sequence of stations expressed in code: named, ordered, and halted as a unit the moment one station fails.
Configuration kept apart from steps
Put settings near the top as named variables, and require the arguments you truly need with the ${name:?message} form, which aborts with your message if the caller omitted them:
ROOT="${1:?usage: scaffold.sh PROJECT}"
DIRS=(src tests docs)
${1:?...} reads "use $1, but if it is unset or empty, print this message and exit non-zero." Listing the step targets in an array like DIRS keeps the data separate from the loop that acts on it, so adding a fourth directory is a one-word edit rather than a code change.
Making a step idempotent
An idempotent step checks the world before changing it, so a second run is a no-op rather than an error or a duplicate:
for d in "${DIRS[@]}"; do
path="$ROOT/$d"
[ -d "$path" ] && echo "exists $path" || mkdir -p "$path"
done
Testing [ -d "$path" ] before creating means the loop reports existing directories and creates only the missing ones. The same pattern -- test, then act only if needed -- makes appending a config line, adding a user, or downloading a file safe to repeat.
Appending a line is the classic case that people get wrong with a bare >>, which duplicates the line on every run. The idempotent form tests first with grep -qxF -- quiet, whole-line, fixed-string -- and appends only when the line is absent:
LINE='export PATH=/opt/bin:$PATH'
grep -qxF "$LINE" profile.txt 2>/dev/null || echo "$LINE" >> profile.txt
Run that once and the line is added; run it a hundred times and profile.txt still contains exactly one copy, because each run finds the line already present and does nothing. The -q suppresses output, -x requires the whole line to match so a substring cannot fool it, and -F treats the pattern as literal text rather than a regex. The next section builds these test-then-act ideas into a complete, re-runnable script.
Real World Example: An Idempotent Project Scaffolder
Teams standardise new projects on the same layout: a src, tests and docs directory under a project root. This scaffold.sh creates that layout, reports what it did, and -- crucially -- is safe to run again on a project that already exists, creating only what is missing.
#!/usr/bin/env bash
# scaffold.sh -- create a standard project layout, safe to re-run
set -euo pipefail
ROOT="${1:?usage: scaffold.sh PROJECT}"
DIRS=(src tests docs)
created=0
for d in "${DIRS[@]}"; do
path="$ROOT/$d"
if [ -d "$path" ]; then
echo "exists $path"
else
mkdir -p "$path"
echo "created $path"
created=$(( created + 1 ))
fi
done
echo "summary: $created created, $(( ${#DIRS[@]} - created )) already present"
The first run on a fresh project creates all three directories:
Output:
created demo/src
created demo/tests
created demo/docs
summary: 3 created, 0 already present
Run it a second time and every directory already exists, so it changes nothing and says so:
Output:
exists demo/src
exists demo/tests
exists demo/docs
summary: 0 created, 3 already present
The design follows the tunnel: a strict-mode preamble as the interlock, configuration (ROOT and the DIRS array) kept apart from the fixed loop, and each step made idempotent by the [ -d "$path" ] test. The created counter accumulates in the current shell because the loop is driven by an in-shell for, so the summary line reports an honest tally. Because the whole procedure is wrapped in test-then-act, the difference between "brand new project" and "half-existing project" is handled by the same code with no special cases.
That idempotency, though, is only skin deep, and that is the script's real flaw. It tests whether each path is a directory, not whether the layout is actually correct, and it copes badly when a path exists as the wrong kind of thing. If demo/tests already exists as a regular file, [ -d "$path" ] is false, so the script tries mkdir -p demo/tests, which fails because a file is in the way. Under set -e the script then aborts mid-loop: on such an input it prints only created demo/src and exits non-zero, leaving docs never created and the summary line never printed. The interlock did its job -- it halted rather than lying about success -- but the result is a genuinely partial scaffold, and a caller that checks only standard output rather than the exit status would not notice the job stopped halfway. A more careful version would detect a non-directory collision and either repair it or fail with a clear message naming the offending path, rather than letting a raw mkdir error be the only signal.
Common Mistakes
- Omitting
set -euo pipefail. Without it a failed step is ignored and the script runs on over broken state, reporting success. Make the strict-mode preamble the second line of every automation script.
- Assuming a step is idempotent when it is not.
mkdir dirfails on the second run,echo line >> fileduplicates the line every run. Test before you act, or use naturally idempotent forms likemkdir -p.
- Mixing configuration into the logic. Hard-coded paths and magic numbers scattered through the steps make the script impossible to retarget. Keep settings in named variables at the top.
- Reading arguments loose at the top of the file instead of in
main. Code that runs before the whole file is parsed can strike before a later syntax error is caught. Put the work inmainand callmain "$@"last.
- Trusting standard output instead of the exit status. A script can print reassuring lines and still have aborted. Callers must check
$?or useset -e, not scrape the log.
- Forgetting
pipefail, so a crashed pipeline stage is hidden.build | tee logreportstee's success even whenbuilddied. Addset -o pipefailso the pipeline fails when any stage does.
- Leaving variable expansions unquoted.
mkdir -p $ROOT/$dbreaks the moment a path contains a space. Quote every expansion:"$ROOT/$d".
- Not requiring mandatory arguments. A script that defaults a missing project name to an empty string can operate on the wrong directory. Use
${1:?message}to demand what you need.
- Making the script non-restartable after a partial run. If a crash leaves half-finished state that the next run cannot recover from, the automation is fragile. Design steps so a re-run repairs rather than compounds the mess.
Best Practices
- Start every script with
set -euo pipefail. It is the interlock that converts silent, ignored failures into an immediate, honest stop.
- Wrap the work in
mainand callmain "$@"last. The whole file is parsed before anything runs, and the argument-reading code lives beside the logic that uses it.
- Separate configuration from steps. Keep paths, defaults and tunables in named variables at the top so behaviour changes without touching the machinery.
- Make every step idempotent. Test the world before changing it so a retried or double-clicked run repairs state instead of duplicating or erroring.
- Require mandatory inputs explicitly.
${1:?usage: ...}refuses to run without the arguments it needs, instead of guessing with an empty default.
- Quote all expansions. Writing
"$ROOT/$d"keeps paths with spaces and odd characters intact through every command.
- Report a truthful summary and a correct exit status. Print what changed and exit non-zero on failure, so both humans and calling scripts can trust the result.
- Design for restartability. Assume the script may die halfway; make sure the next run can pick up cleanly rather than tripping over half-finished state.
Practice Exercises
- Add a fourth directory. Extend
scaffold.shto also create aconfigdirectory by editing only theDIRSarray, then run it on a fresh project and on an existing one to confirm the summary counts adjust correctly.
- Prove the interlock. Write a two-step script with and without
set -ewhere the first step fails, and show that only the strict-mode version stops before the second step runs.
- Make an append idempotent. Write a step that adds the line
export PATH=/opt/bin:$PATHto a file only if it is not already present, and show that running it three times leaves exactly one copy of the line.
- Reproduce the partial-run flaw. Create a project where
testsalready exists as a regular file, runscaffold.shon it, and show from the exit status and the directory listing that the run stopped halfway. Then describe the check you would add to handle it cleanly.