A typical handoff script has four lines that fail silently, from a cd into an unmounted directory to an rm -rf that could wipe the root filesystem.
Key Takeaways
- Without pipefail, the failure of the first command in a pipeline is ignored: if pg_dump fails, gzip still writes out a file and returns 0.
- set -e is only a safety net: it does not trigger inside if conditions or && and || lists, and calling functions inside conditionals is a documented trap.
- ShellCheck follows standard exit codes and can be plugged directly into CI, catching missing quotes, rm -rf on empty variables, and failed cd commands.
Three weeks into the deployment, the customer's ops team needs to restore data using the backup script left for them. Cron has been running it every night, and every morning the log says "Backup OK". But the archive they open is empty.
The script never crashed. It simply kept running after a step failed, which is bash's most dangerous behavior. For a Forward Deployed Engineer (FDE), handoff scripts run long after the project ends, on machines no one on the team manages, processing data no one on the team has seen.
So the skill that really matters is not writing elegant bash, but writing bash that stops and reports clearly when something goes wrong, instead of continuing in a broken state.
One script, four failure points, not a single error message
Here is the "works on my laptop" version everyone has written:
#!/bin/bash BACKUP_DIR=/data/backups cd $BACKUP_DIR rm -rf $STAGING_DIR/* pg_dump "$DB_URL" | gzip > nightly.sql.gz echo "Backup OK"
Line 3 is the first failure. If
/data/backups
is not mounted,
cd
fails, yet the script keeps going. The ShellCheck wiki (code SC2164) warns about exactly this: everything afterward happens in the wrong directory.
Line 4 is worse. The customer's cron usually does not load the environment variables your shell loads, so
STAGING_DIR
may be empty. The command then becomes
rm -rf /*
, and the SC2115 wiki page puts it bluntly: it deletes everything under the root directory.
Unquoted variables also trigger SC2086: when filenames contain spaces or wildcards (common in customer data), the script breaks.
Line 5 is why the backup file is empty. If
pg_dump
fails due to a wrong password,
gzip
still compresses an empty data stream and exits with 0. The pipeline's return status depends on the last command, so line 6 still prints "Backup OK".
What the first three options can and cannot do
The first line of defense is
set -euo pipefail
. According to the Bash Reference Manual,
-e
(errexit) makes the shell exit when a pipeline, a list, or a compound command returns a non-zero status.
-u
treats use of an unset variable as an error, prints a message to stderr, and exits in non-interactive shells, so a misspelled variable name is caught immediately.
pipefail
fixes the problem on line 5. The manual notes that this option is disabled by default. When enabled, the pipeline's return status is the status of the last (rightmost) command to exit with a non-zero status; when disabled,
set -e
ignores the failure of every command in a pipeline except the last one.
However, these three options are not a guarantee. The same manual lists cases where
set -e
does not trigger:
if
in the condition of an if statement, and
&&
any command in an
||
or
&&
any command in an
||
or
. BashFAQ/105 on Wooledge describes these rules as extremely intricate, and they even change between Bash versions.
set -e
The FAQ also highlights a particularly dangerous trap: combining
if run_backup; then ...
with functions called inside conditionals. A script that wraps all its main logic in
falls right into it, so do not expect errexit to protect anything that happens inside a function.
set -e
。
.
After the rewrite, every failure makes itself heard
set -euo pipefail
The right approach is to treat
#!/usr/bin/env bash
set -euo pipefail
: "${DB_URL:?未设置 DB_URL}"
: "${STAGING_DIR:?未设置 STAGING_DIR}"
BACKUP_DIR="/data/backups"
cd "$BACKUP_DIR" || { echo "无法进入目录 $BACKUP_DIR" >&2; exit 1; }
tmp="$(mktemp "$BACKUP_DIR/nightly.XXXXXX")"
trap 'rm -f "$tmp"' EXIT
rm -rf "${STAGING_DIR:?}"/*
if ! pg_dump "$DB_URL" | gzip > "$tmp"; then
echo "pg_dump 失败,保留上一次的备份" >&2
exit 1
fi
mv "$tmp" nightly.sql.gz
echo "Backup OK"as a safety net, then add explicit checks around every step that could corrupt data:
:
The first two lines of
DB_URL
validate configuration variables at startup. If
rm
is missing, the script stops with a message the ops team can understand, instead of dying halfway through.
${STAGING_DIR:?}The
/*
。
cd ... || exit
.
set -e
is the fix for SC2164. Even with
already in place, write it explicitly here, because safety should not depend on those intricate rules above.
mktemp
The file-writing step is the part people most often skip. Data is first written to a temporary file created with
mv
, and only when the pipeline succeeds is the old backup replaced with
.
mktemp
BashFAQ/062 stresses that the tool must actually create files atomically, not just return an unused filename, and
mv
does exactly that. Creating the temporary file inside the target directory guarantees that
completes on the same filesystem.
trap '...' EXIT
No matter how the script exits,
pg_dump
removes the temporary file.
if !
On failure, the previous night's backup remains intact, no leftover files are left behind, cron receives exit code 1 and raises an alert. Note that
disables errexit for this pipeline, so the explicit check here is a necessity, not decoration.
Let ShellCheck read it before the customer does
shellcheck
However careful you are, a quote will slip through. ShellCheck is a static analysis tool for bash/sh scripts. It follows the standard exit code convention, so adding a single
command to your workflow turns CI red as soon as any warning appears.
shellcheck backup.sh
Running
cd
on the old version produces warnings on exactly the lines analyzed above, such as SC2086 for unquoted variables and SC2164 for the unchecked
.
rm -rf
Each code has a wiki page explaining the cause and the fix. Reading these pages (including SC2115 on empty variables
) is the fastest way to learn defensive bash.
set -euo pipefail
The pre-handoff routine check for every script has four steps, matching the four layers in the diagram at the top. Step one is
${var:?message}. Step two is adding explicit checks: at the top of the file, write
cd
for every configuration variable, and add
|| exit
。
and any command whose failure would break the next step.
trap
Step three is writing to a temporary file before renaming, paired with a
that handles cleanup. Finally, run ShellCheck in the handoff repository's CI.
Mistakes that let "safe" scripts still destroy data
set -e
The most common one is trusting
if
completely, then wrapping the main logic in a function called from an
|| return 1
, which is exactly the trap BashFAQ/105 warns about. If you need to branch on a function's result, check for errors inside the function with
.
env -i bash backup.sh
Another mistake is testing only on your own machine, where all environment variables are already set. Run with
For career development, this detail is worth putting on your resume or portfolio: "The handover script runs ShellCheck in CI, returns a clear exit code on failure, and never overwrites data when something goes wrong."
In an FDE interview, if you get the chance to explain how you made the things you left behind keep working after you're gone, let the results speak. A small repository containing both versions of the script above, with one commit per fixed warning, is more convincing than any self-description.
This week's exercise
Find a script you've handed over, delete a configuration variable to make the first command in the pipeline fail, and run it again. If the logs still report success, your client is trusting a line of text that isn't true.
Was this article helpful?
Thanks for your feedback!