It is 6:40 p.m. on a Friday, and the backup script you wrote months ago has just done something unforgivable. It was supposed to clean up an old directory. Instead, a variable was empty, and the command that should have read rm -rf /srv/app/old_releases/* quietly became rm -rf /srv/app/*. No error. No warning. The script printed "Done!" and exited with a cheerful status of zero.

If you have written shell scripts for any length of time, you have either lived through a version of this story or you are about to. Bash is wonderfully quick for glue work, but its defaults are tuned for typing commands interactively, not for running unattended. By default, it keeps going after errors, treats unset variables as empty strings, and reports the success of only the last command in a pipeline.

The fix is a short incantation you will see at the top of many professional scripts. This guide explains what each part does, why it helps, and where it can still bite you.

The one-line safety net

Here is the line, followed by a minimal script that uses it:

#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'

That is the whole thing. Three options packed into set -euo pipefail, plus a tighter word-splitting rule. Together they turn Bash from a forgiving shell into a careful one.

A script that fails loudly on line 4 is a gift. A script that fails silently on line 4 and corrupts data on line 40 is a postmortem.

Let's take the options one at a time, because understanding why each exists will help you debug the surprises later.

set -e: stop when something fails

Without -e, Bash shrugs off failures. Consider this fragment:

cd /srv/app/releases
rm -rf ./old/*

If the cd fails because the directory does not exist, Bash prints an error and then continues. The rm now runs in whatever directory you happened to be in. That is how people delete the wrong folder.

With set -e (also written set -o errexit), the script exits immediately when a simple command returns a non-zero status. The failed cd ends the script before the rm is ever reached.

There is a catch, and it is an important one. -e does not trigger inside conditions. Commands in an if test, on the left side of && or ||, or in a while condition are allowed to fail, because Bash assumes you are checking the result on purpose. That means this still "works" even with -e on:

if ! backup_database; then
    echo "backup failed, continuing anyway"
fi

That is usually what you want. Just remember that a function called inside an if runs with -e effectively switched off for its entire body, which surprises many people.

set -u: unset variables are errors

This option targets the exact bug from the opening. By default, a typo like $RELEASE_DIRR expands to nothing. With set -u (nounset), Bash aborts with a clear message such as RELEASE_DIRR: unbound variable.

Compare the two behaviors:

# Without -u: dangerous
rm -rf "$TARGET_DIR"/*      # TARGET_DIR is empty -> rm -rf /*

# With -u: the script stops before running rm

Sometimes a variable is legitimately optional. For those cases, use a default value with ${VAR:-default}, or the empty-default form ${VAR:-}:

LOG_LEVEL="${LOG_LEVEL:-info}"
if [[ -n "${DEBUG:-}" ]]; then
    set -x
fi

You can even demand a value and give a helpful message when it is missing:

: "${DEPLOY_ENV:?DEPLOY_ENV must be set, e.g. staging or production}"

That single line documents a requirement and enforces it. It is one of the best small habits you can pick up.

set -o pipefail: don't let a pipeline hide failure

Here is the subtle one. In a pipeline such as curl ... | grep ... | wc -l, Bash normally reports the exit status of only the final command. So a failed curl is invisible as long as wc succeeds.

# Without pipefail, this "succeeds" even if the database dump fails
mysqldump mydb | gzip > backup.sql.gz
echo "exit status: $?"

If mysqldump crashes halfway, gzip still happily compresses the partial output and returns zero. You now have a corrupt backup that looks fine, which is the worst kind. With pipefail, the pipeline's status becomes that of the last command that failed, so set -e can catch it.

The most dangerous backup is the one that reports success.

One practical wrinkle: grep returns 1 when it finds no matches, and with pipefail that can kill your script even though "no matches" is a perfectly normal outcome. When that is acceptable, guard it explicitly:

count=$(grep -c "ERROR" app.log || true)

The || true says "I know this might fail, and that's fine." It is deliberate, visible, and searchable, which is exactly the point.

Quote everything, and tighten word splitting

Strict mode catches errors, but it does not fix Bash's other famous trap: word splitting. An unquoted variable is split on whitespace, so a filename with a space becomes two arguments.

file="My Report.pdf"
rm $file        # tries to delete "My" and "Report.pdf"
rm "$file"      # deletes the one file you meant

The rule is simple: always put double quotes around variable expansions unless you specifically want splitting. Setting IFS=$'\n\t' (removing the space as a separator) adds a second layer of protection for loops and arrays, though quoting remains your primary defense.

For arrays, the safe expansion is "${items[@]}":

files=("a b.txt" "c.txt")
for f in "${files[@]}"; do
    echo "Processing: $f"
done

Clean up after yourself with trap

Scripts that create temporary files should remove them even when something goes wrong. Strict mode makes early exits more common, so pair it with a trap:

tmpdir="$(mktemp -d)"
cleanup() {
    rm -rf "$tmpdir"
}
trap cleanup EXIT

# ... do work inside "$tmpdir" ...

The EXIT trap runs whether the script finishes normally, hits an error under set -e, or is interrupted. Notice the use of mktemp -d rather than a hand-made name like /tmp/work, which avoids collisions and predictable-path problems. And because tmpdir is set before the trap, -u will not complain about it.

A realistic template you can copy

Putting it all together, here is a small but sturdy skeleton for a backup-style script. All values are samples:

#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'

: "${BACKUP_DIR:?BACKUP_DIR must be set}"
DB_NAME="${1:?usage: $0 <database-name>}"

timestamp="$(date +%Y%m%d-%H%M%S)"
outfile="${BACKUP_DIR}/${DB_NAME}-${timestamp}.sql.gz"
tmpfile="$(mktemp)"

cleanup() { rm -f "$tmpfile"; }
trap cleanup EXIT

echo "Dumping ${DB_NAME}..."
mysqldump --single-transaction "$DB_NAME" | gzip > "$tmpfile"

mv "$tmpfile" "$outfile"
echo "Wrote ${outfile}"

Notice what the structure buys you. The script refuses to run without its inputs, writes to a temporary file first, and only moves the finished result into place if every step succeeded. Readers never see a half-written backup, which is a pattern worth stealing for any script that produces output.

Where strict mode still falls short

It is worth being honest about the limits, so you do not develop false confidence.

SituationWhat happensBetter approach
Failure inside $(...) assigned in local x=$(cmd)Exit status is masked by localDeclare first: local x; x=$(cmd)
Command in an if or && chain-e is ignored thereCheck status explicitly
Subshell or process substitutionErrors may not propagateUse wait and test results
Very large scriptsHard to reason aboutConsider Python

That last row deserves a moment. Bash is excellent up to a point, and strict mode extends that point considerably. But if your script needs data structures, heavy string parsing, or real error handling, switching to Python is a mark of good judgment, not defeat. A useful rule of thumb: once a script passes roughly a hundred lines or needs a nested data structure, reconsider the language.

You can also lint your work. A tool called ShellCheck reads your script and flags unquoted variables, risky rm usage, and many of the pitfalls above, often with a link explaining the fix. Running it in your editor or CI pipeline is perhaps the highest-value five minutes you can spend on shell hygiene.

Debugging strict-mode scripts

When a script exits unexpectedly under -e, the silence can be puzzling. Two tricks help. First, run it with bash -x script.sh to print each command as it executes. Second, add an error trap that reports the failing line:

trap 'echo "Error on line $LINENO" >&2' ERR

Combined, these two usually pinpoint the culprit within a minute. Print messages to stderr (>&2) so they do not get mixed into any output your script is meant to produce.

Summary

Bash's defaults favor convenience over safety, and scripts that run unattended deserve the opposite. Start every non-trivial script with set -euo pipefail, quote your variables, use trap for cleanup, and write results to a temporary file before moving them into place. Know the edge cases (conditions, local, subshells), lint with ShellCheck, and move to Python when complexity grows.

None of this makes you immune to mistakes, but it changes how mistakes behave: from silent and destructive to loud and early. The next time a variable turns up empty on a Friday evening, you will get an error message instead of a long weekend. That is a trade worth making.