Quoting, strict mode, tracing with set -x and failing loudly
Make Bash scripts fail loudly with set -euo pipefail, quote expansions correctly, run ShellCheck and fix its findings to zero, trace with set -x, and clean up with traps.
Contentsand lesson path
On this page
- The Unofficial Bash Strict Mode: set -euo pipefail
- Quoting Discipline and Variable Masking Hazards
- Exercise: run ShellCheck and fix a script to zero findings
- Execution Tracing with set -x and Cleanup Traps
- Check your understanding
- Apply it
- Review prompt
Lessons of Scripting Basics
- Anatomy of a script: shebang, arguments and exit codes Concept · 15 min
- Control flow you will actually use: tests, case, loops, functions, read and command substitution Worked example · 25 min
- Quoting, strict mode, tracing with set -x and failing loudly Worked example · 20 min
- Lab: an idempotent backup job with logging and a schedule Lab · 30 min
- Beyond Bash: jq, yq and porting a script to Python Worked example · 25 min
- Check: review and repair a fragile script Knowledge check · 8 questions
What you will learn
- Make a script robust with strict mode, correct quoting, error traps and idempotent steps, and keep it free of ShellCheck warnings.
Prerequisites: Linux CLI
01. The Unofficial Bash Strict Mode: set -euo pipefail
By default Bash keeps going after a command fails, treats a misspelled variable as an empty string, and reports a pipeline as successful when only its last command succeeded. In automation, that is how a failed download turns into a half-applied deployment. Most teams therefore start scripts with the so-called unofficial strict mode, three options set on line 2:
-
-e(errexit) exits when a command fails and nothing checks its status, for example a failed download ormkdir. It has many exceptions, which is why it surprises people:-eis suspended insideif,whileanduntilconditions, for every command of an&&or||list except the last, after!, inside a function called from any of those contexts (the whole function body then runs without-e), and whenlocal,exportordeclarehides a failing$(...). An explicit|| truealso suppresses it, on purpose. Treatset -eas a safety net and check critical commands explicitly. -
-u(nounset) makes expanding an unset variable an error that stops the script. Consider the cleanup commandrm -rf "$BACKUP_DIR"/*, with the glob outside the quotes so that it matches the directory's contents. (Inside the quotes, as in"${BACKUP_DIR}/*", the*is never expanded: the command would try to delete a file literally named*and silently clean up nothing.) IfBACKUP_DIRis unset or empty, the command becomesrm -rf /*and starts deleting the root filesystem. Underset -u, an unset variable stops the shell withBACKUP_DIR: unbound variablebeforermruns.set -udoes not catch a variable that is set but empty, so writerm -rf "${BACKUP_DIR:?}"/*: the:?aborts withBACKUP_DIR: parameter null or not setwhen the variable is unset or empty (ShellCheck warns about the unprotected form as SC2115). When you legitimately need to test whether an optional variable is set without triggering a nounset abort, use the parameter expansion test${VAR+x}or the Bash 4.2+ builtin condition[[ -v VAR ]]. -
-o pipefailchanges the status of a pipeline. Normallygrep ERROR app.log | wc -lreports the status ofwc, the last command, so a missingapp.loggoes unnoticed. Withpipefail, the pipeline returns the status of the rightmost command that failed.
Together they make a script stop near the line that went wrong, instead of carrying on with bad data.
#!/usr/bin/env bash
set -euo pipefail
# Provide fallback default if variable is unset or empty
DEPLOY_ENV="${DEPLOY_ENV:-staging}"
# Abort with explicit custom error message if variable is missing
: "${DATABASE_PASSWORD:?CRITICAL: DATABASE_PASSWORD must be set}"
# Safely loop over an optional array: zero iterations when unset or empty.
# ("${EXTRA_ARGS[@]:-}" would loop once with an empty item.)
for item in ${EXTRA_ARGS[@]+"${EXTRA_ARGS[@]}"}; do
echo "Processing argument: ${item}"
done02. Quoting Discipline and Variable Masking Hazards
Bash splits every unquoted expansion into words and then expands any wildcards in them. Three cases cover almost every script:
- Single quotes (
'...') keep every character literally: no$VAR, no$(cmd). Use them for fixed text and forawkorsedprograms. - Double quotes (
"...") expand variables and command substitutions, but the result stays one argument, spaces and*included. Quote every variable that holds a path, user input or command output. - Unquoted
$VARis split on spaces, tabs and newlines, and each piece is matched as a file pattern. A file calledmy app.logbecomes two arguments. Treat an unquoted expansion as a bug unless you want splitting.
You do not have to spot these by eye: ShellCheck, a static analyser, finds them for you, as the next section shows.
03. Exercise: run ShellCheck and fix a script to zero findings
ShellCheck reads a script without running it and reports likely bugs. Each finding has a code such as SC2086, a severity (error, warning, info or style) and a page on the ShellCheck wiki that explains it. Install it with sudo apt install shellcheck, or download the static binary from the ShellCheck releases page. The output below comes from ShellCheck 0.11.0; older versions word some messages differently.
Save this short cleanup script as clean-cache.sh. It runs, but it has three bugs.
#!/usr/bin/env bash
# clean-cache.sh DIR: report how many files a cache holds, then empty it
set -euo pipefail
cache_dir=$1
count_files() {
local count=$(find "$1" -type f | wc -l)
echo "Files before cleaning: $count"
}
count_files $cache_dir
rm -rf "$cache_dir"/*
echo "Emptied $cache_dir"shellcheck clean-cache.sh; echo "exit=$?"
In clean-cache.sh line 8:
local count=$(find "$1" -type f | wc -l)
^---^ SC2155 (warning): Declare and assign separately to avoid
masking return values.
In clean-cache.sh line 12:
count_files $cache_dir
^--------^ SC2086 (info): Double quote to prevent globbing and
word splitting.
Did you mean:
count_files "$cache_dir"
In clean-cache.sh line 13:
rm -rf "$cache_dir"/*
^------------^ SC2115 (warning): Use "${var:?}" to ensure this never
expands to /* .
For more information:
https://www.shellcheck.net/wiki/SC2115 -- Use "${var:?}" to ensure this nev...
https://www.shellcheck.net/wiki/SC2155 -- Declare and assign separately to ...
https://www.shellcheck.net/wiki/SC2086 -- Double quote to prevent globbing ...
exit=1Read each finding as where, what and why: the line, a caret under the exact text, then the code, severity and message. The exit status is 1 whenever there is at least one finding, which is what lets CI fail a build.
- SC2155 is the
localmasking trap from the callout above: iffindfailed, the script would carry on. - SC2086 flags the unquoted
$cache_dir: a directory calledmy cachewould arrive as two arguments. - SC2115 flags
rm -rf "$cache_dir"/*. If the variable were ever empty, the command would becomerm -rf /*.${cache_dir:?}stops the script instead.
Fix the three lines and validate the argument at the top. The last two lines show the one case where a finding is wrong: the single quotes are deliberate, because the text is meant for the reader to paste into their own shell, but ShellCheck reports SC2016 (expressions do not expand in single quotes). Silence it for that one command with a directive comment, and give the reason after a second #. A directive placed directly after the shebang would apply to the whole file, which hides future real bugs.
#!/usr/bin/env bash
# clean-cache.sh DIR: report how many files a cache holds, then empty it
set -euo pipefail
cache_dir=${1:?usage: clean-cache.sh DIR}
count_files() {
local count
count=$(find "$1" -type f | wc -l)
echo "Files before cleaning: $count"
}
count_files "$cache_dir"
rm -rf "${cache_dir:?}"/*
echo "Emptied $cache_dir"
# shellcheck disable=SC2016 # literal on purpose: the reader's shell expands it
echo 'To use the tools, run: export PATH="$HOME/.cache/tools:$PATH"'shellcheck clean-cache.sh && echo 'shellcheck: no findings'
chmod +x clean-cache.sh # without the execute bit, ./ gives Permission denied
mkdir -p demo-cache && touch demo-cache/a.tmp demo-cache/b.tmp
./clean-cache.sh demo-cache && ls -A demo-cacheshellcheck: no findings
Files before cleaning: 2
Emptied demo-cache
To use the tools, run: export PATH="$HOME/.cache/tools:$PATH"In CI, run ShellCheck on every script and let its exit status fail the job, for example shellcheck scripts/*.sh. You will often see shellcheck -S warning, which reports only warning and error findings. It is a common way to adopt ShellCheck on a large, old codebase, but know what it hides: on the before script it still fails on SC2155 and SC2115, yet the quoting finding SC2086 disappears, because ShellCheck rates it info. If the goal is a script free of findings, run the default severity locally and in CI, and treat each disable comment as a reviewed exception with a reason.
04. Execution Tracing with set -x and Cleanup Traps
When debugging complex automated scripts in headless CI/CD runners or background jobs, enable execution tracing with set -x. This prints each executed command and its evaluated arguments prefixed with + to standard error prior to execution. To make traces easily readable across large repositories, customize the PS4 prompt variable to include the filename and source code line number.
To clean up temporary staging directories, background SSH tunnels or lockfiles even when a script stops midway, register an EXIT pseudo-signal trap as soon as the resource is allocated. The EXIT trap runs when the script ends normally, calls exit, or stops under set -e. What happens on a signal depends on the shell: Bash (tested with 5.1) also runs it when the script is killed by SIGTERM or SIGINT, but a POSIX sh such as Dash does not. Nothing runs on SIGKILL, which is what docker stop and Kubernetes send when the grace period runs out.
So make the signal handling explicit: trap 'exit 143' TERM and trap 'exit 130' INT turn each signal into a normal exit, which then runs the EXIT trap in every shell and keeps the conventional exit codes. Bash runs a trap only after the current foreground command finishes, so start a long command as long_command & wait $! if the script must react to SIGTERM quickly. Because nothing can run on SIGKILL, design locks and markers so that a later run can detect and remove stale ones.
#!/usr/bin/env bash
set -euo pipefail
# Set line-numbered trace formatting for debugging
export PS4='+ [${BASH_SOURCE##*/}:${LINENO}] '
# Create temporary working directory
WORK_DIR=$(mktemp -d)
# Clean up on exit: success, error under set -e, or the signals trapped below
cleanup() {
local exit_code=$?
echo "Cleaning up temporary scratch space: ${WORK_DIR}"
rm -rf "${WORK_DIR}"
exit "${exit_code}"
}
trap cleanup EXIT
trap 'exit 143' TERM # turn signals into a normal exit, so cleanup runs
trap 'exit 130' INT
echo "Executing workflow inside ${WORK_DIR}..."05. Check your understanding
06. Apply it
Take one script you already use, or the health check from this skill's practice task:
- Add
set -euo pipefailon line 2 and give optional variables a default (${VAR:-default}) or a check (${VAR:?message}). - Register
trap cleanup EXIT(plustrap 'exit 143' TERMandtrap 'exit 130' INT) as soon as you create a temporary folder or lock file. - Run
shellcheckuntil it prints nothing, keeping anydisablecomment scoped to one command with a reason, then add the same command to your CI job.
07. Review prompt
Explain each component of set -euo pipefail and the risk each flag reduces. Why does local var=$(cmd) mask errors under set -e, and which ShellCheck code reports it? What does shellcheck -S warning leave out, and where should a disable directive go? Describe how to structure a cleanup trap that removes temporary files whether the script succeeds, fails or is stopped with SIGTERM, and what still leaks on SIGKILL.
References
- Greg's Wiki: BashFAQ/105 (why set -e does not do what you expect)
- ShellCheck wiki: SC2155, Declare and assign separately to avoid masking return values
- Linux manual page: set(1p)
- ShellCheck wiki: Directive (scope of disable comments)
- ShellCheck wiki: SC2115, Use "${var:?}" to ensure this never expands to /*
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.