Making Shell Scripts Safer With Strict Mode
By default, a Bash script keeps going after something fails. A command returns an error, the next line runs anyway, and the script may finish with a cheerful exit code while it has deleted the wrong folder or copied nothing at all. That forgiving behaviour is fine at an interactive prompt, but in a saved script it hides problems.
Strict mode is a small set of options that make Bash stop and complain when something goes wrong. This article explains each one, what it does not cover, and the other habits that make scripts safer.
The usual three lines
Many scripts begin like this:
#!/usr/bin/env bash
set -euo pipefail
That single set command turns on three separate behaviours. We will look at each in turn, since they solve different problems.
set -e: exit on error
With -e, the script exits immediately when a simple command returns a non zero status. Without it, this script would try to remove files in the wrong place after the cd failed:
cd /some/missing/folder
rm -rf ./*
With -e, the failed cd ends the script before the dangerous rm runs. That is the main point of the option: failures stop the line of execution rather than letting later commands act on wrong assumptions.
There are exceptions you should know about. The -e option is ignored inside conditions, so a failing command inside an if test, or on the left of && or ||, does not stop the script. Some commands also return non zero in normal cases, such as grep when it finds no match. Handle those on purpose:
if grep -q "ready" status.txt; then
echo "ok"
fi
count=$(grep -c "error" app.log || true)
The || true at the end says "a failure here is acceptable." Use it sparingly, and only where you have decided it really is.
set -u: unset variables are errors
By default, Bash treats a variable that was never set as an empty string. A typo then turns into silent damage. The classic example:
rm -rf "$BUILD_DIR/"
If BUILD_DIR was never set because of a typo or a missing argument, this becomes rm -rf "/". With -u, Bash stops with an "unbound variable" error before anything runs. When you do want a default value, say so explicitly with ${NAME:-default}, and when a value is required, use ${NAME:?message} to print a helpful error.
set -o pipefail: errors inside pipelines count
Normally the exit status of a pipeline is the status of its last command only. So in curl "$url" | sort, a failed download goes unnoticed because sort succeeded on empty input. With pipefail, the pipeline fails if any step fails, which lets -e catch the problem.
What strict mode does not do
It is helpful, but it is not a safety guarantee. The behaviour of -e has surprising corners, and some experts avoid relying on it alone. Treat it as a net that catches obvious mistakes, and pair it with explicit checks for operations that matter. For example, test that a folder exists before deleting inside it, and check the exit code yourself after commands whose failure needs a specific message.
Quote every expansion
Unquoted variables are split on spaces and expanded as wildcards, which causes many real world accidents. A file named old report.txt becomes two arguments if you write rm $file. Write rm "$file" instead. Quoting is the single most valuable habit in shell scripting. Using "$@" rather than $* keeps arguments intact when you pass them along to another command.
Clean up with trap
Scripts that create temporary files should remove them even when they stop early. The trap command runs a handler when the script exits.
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
echo "working in $tmp"
The EXIT trap runs on normal completion and on errors that end the script under -e. The mktemp command creates a unique, safe location, which is better than a fixed name in /tmp that another process might guess or overwrite.
More habits worth adopting
- Run ShellCheck, a widely used open source linter, to catch quoting errors and other pitfalls before they reach production.
- Use
[[ ... ]]tests in Bash scripts, since they behave more predictably than single brackets with unquoted values. - Print errors to standard error with
echo "message" >&2, so normal output stays clean. - Prefer
mktempover guessed file names, and--before file arguments to stop names beginning with a dash from being read as options. - Check inputs at the top of the script and exit with a clear usage message.
- Do a dry run mode that prints destructive commands instead of running them.
A short template
#!/usr/bin/env bash
set -euo pipefail
usage() { echo "Usage: ${0} <source> <dest>" >&2; exit 2; }
[ $# -eq 2 ] || usage
src=${1}
dest=${2}
[ -d "$src" ] || { echo "No such folder: $src" >&2; exit 1; }
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
cp -a "$src/." "$tmp/"
mv "$tmp" "$dest"
This version validates its inputs, fails loudly, and cleans up after itself.
Frequently Asked Questions
Does strict mode work in plain sh scripts?
The -e and -u options exist in POSIX shells, but pipefail was historically a Bash extension and is only available in newer versions of other shells. If you use pipefail, make sure your shebang names Bash.
Why did my script not exit even with set -e?
The option does not apply inside if conditions, while tests, or commands joined with && and ||. A failure in those positions is treated as part of a decision, not as a fatal error.
Should every script use strict mode?
Most non trivial scripts benefit from it. For a one-line helper, it may add no value, and for scripts that deliberately ignore errors, it may need frequent exceptions. Use judgment, and test the script to see how it behaves.