It is 11:40 p.m. and you are proud of yourself. You wrote a tiny shell script to clean up old build folders on your server, tested it once, and scheduled it. Three weeks later a teammate asks why the deploy directory is empty. The script had a typo in a variable name, the variable expanded to nothing, and rm -rf "$BUILD_DIR/" quietly became rm -rf / territory, minus the safety net you thought you had.

Shell scripts are wonderful glue, but by default Bash is incredibly forgiving. It will keep running after a command fails, treat unset variables as empty strings, and happily hide errors inside pipelines. That forgiveness is exactly what turns a small typo into a bad night. The good news: a handful of habits make your scripts fail loudly and early, which is what you want from automation.

A script that stops at the first surprise is a script you can trust. A script that keeps going is a script you have to babysit.

Start with the "strict mode" header

Most reliable Bash scripts begin with the same three lines. Think of them as a seatbelt you buckle before driving.

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

Each flag solves a specific problem, so it helps to know what you are getting.

  • set -e exits the script as soon as a command returns a non-zero status.
  • set -u treats an unset variable as an error instead of silently expanding to an empty string.
  • set -o pipefail makes a pipeline fail if any command in it fails, not just the last one.
  • set -E makes the ERR trap work inside functions and subshells too.
  • Setting IFS to newline and tab stops Bash from splitting filenames on spaces.

Why does this matter in practice? Take grep error app.log | sort | uniq -c. Without pipefail, if grep cannot find the file, the pipeline still reports success because uniq ran fine. Your monitoring says "all good" while the log file is missing. With pipefail, the failure surfaces immediately.

A quick honest caveat: set -e has quirks. It does not trigger inside if conditions, && / || chains, or commands whose result you test. It is a safety net, not a guarantee, so treat it as the first layer rather than the only one.

Quote everything, because spaces are everywhere

The single most common Bash bug is an unquoted variable. Filenames contain spaces more often than you expect, especially on files that came from a laptop or a download folder.

file="My Report 2026.pdf"

# Wrong: Bash sees three separate arguments
rm $file

# Right: one argument, exactly as intended
rm -- "$file"

Notice the -- after rm. It tells the command "everything after this is a filename, not an option." Without it, a file named -rf could be interpreted as a flag. It sounds paranoid until you process user-uploaded files, at which point it is simply good manners.

As a rule of thumb, wrap every variable expansion in double quotes unless you specifically want word splitting. For lists, use arrays instead of space-separated strings:

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

The "${files[@]}" form expands to each element as its own properly quoted word. It is a small pattern that prevents a large class of bugs.

Guard against empty variables before dangerous commands

Remember the opening story? Two small defenses would have saved the day. The first is set -u, which stops the script if BUILD_DIR is not defined. The second is the ${var:?message} expansion, which aborts with a custom error when a variable is unset or empty.

BUILD_DIR="${1:?Usage: cleanup.sh <build-dir>}"

# Extra paranoia: refuse to touch anything that is not clearly ours
case "$BUILD_DIR" in
  /srv/builds/*) ;;
  *) echo "Refusing to clean $BUILD_DIR" >&2; exit 1 ;;
esac

find "$BUILD_DIR" -mindepth 1 -maxdepth 1 -mtime +14 -exec rm -rf -- {} +

Here is the claim, the reason, and the example in one place. Destructive commands deserve a whitelist. The reason is that a bug in your logic is far more likely than a bug in rm. The example is the case statement above, which only allows paths under /srv/builds/. If someone passes / or an empty string, the script refuses to run. Three extra lines buy a very large amount of peace.

Clean up after yourself with trap

Scripts often create temporary files or lock files. If the script dies halfway, those leftovers pile up and sometimes block the next run. The trap builtin lets you register cleanup code that runs no matter how the script exits.

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

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

Two things are happening here. The EXIT trap runs on success, on failure, and on most signals, so the temp directory always disappears. The ERR trap prints the line number where something went wrong, which turns a mysterious "it stopped" into a precise place to look. Use mktemp instead of inventing names like /tmp/work, because fixed names collide when two runs overlap.

If your script should never run twice at once (a nightly backup, for example), a lock is cheap insurance:

exec 9>/var/lock/backup.lock
flock -n 9 || { echo "Already running" >&2; exit 1; }

The flock utility releases the lock automatically when the script ends, so you do not need a manual cleanup step.

Log like a future you will have to debug it

When a script fails at 3 a.m., the person reading the output is future you, half asleep and slightly annoyed at past you. Be kind to them. Add timestamps, send errors to stderr, and print what the script is about to do.

log() { printf '%s %s\n' "$(date '+%F %T')" "$*"; }
err() { log "ERROR: $*" >&2; }

log "Starting cleanup of $BUILD_DIR"

Many people also add a dry-run mode. It is one of the most underrated features in any automation script. Instead of deleting, the script prints what it would delete:

DRY_RUN="${DRY_RUN:-0}"
run() {
  if [[ "$DRY_RUN" == "1" ]]; then
    log "[dry-run] $*"
  else
    "$@"
  fi
}

run rm -rf -- "$old_dir"

Run it first with DRY_RUN=1 ./cleanup.sh /srv/builds/app, read the output, and only then run it for real. That single habit has probably saved more data than any backup tool.

Lint it before you trust it

You do not have to memorize every pitfall. ShellCheck is a free static analyzer that reads your script and points out quoting mistakes, unused variables, and risky patterns, usually with a link explaining why.

sudo apt install shellcheck     # Debian/Ubuntu
shellcheck cleanup.sh

A sample warning looks like SC2086: Double quote to prevent globbing and word splitting. That message alone catches the bug from the earlier rm $file example. Many editors can run ShellCheck as you type, and you can add it to a CI job so a risky script never reaches production.

Also know when to stop. Bash is great for gluing commands together, but once a script needs complex data structures, JSON parsing, or real error handling, a language like Python is usually the calmer choice. A good rule is that if your script passes a hundred lines or starts using associative arrays heavily, it is time to consider switching.

A tiny template you can copy

Here is everything above combined into a starting point. Replace the body and keep the skeleton.

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

log() { printf '%s %s\n' "$(date '+%F %T')" "$*"; }
trap 'log "Failed on line $LINENO" >&2' ERR

TARGET="${1:?Usage: $0 <target-dir>}"
DRY_RUN="${DRY_RUN:-0}"
tmpdir="$(mktemp -d)"
trap 'rm -rf -- "$tmpdir"' EXIT

log "Working on $TARGET (dry-run=$DRY_RUN)"
# ... your logic here ...
log "Done"

The short version

Bash will not protect you from yourself, so you build the protection in. Start with set -Eeuo pipefail, quote every variable, validate inputs before anything destructive, clean up with trap, log clearly, add a dry-run switch, and let ShellCheck review your work. None of it takes long, and together these habits move a script from "works on my machine" to "safe to run while I sleep."

The next time you write a quick one-liner for a server, spend two extra minutes on the seatbelt. Your future self, and your deploy directory, will thank you.