Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Worked example · 20 min · revision 3

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

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 or mkdir. It has many exceptions, which is why it surprises people: -e is suspended inside if, while and until conditions, 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 when local, export or declare hides a failing $(...). An explicit || true also suppresses it, on purpose. Treat set -e as a safety net and check critical commands explicitly.

  • -u (nounset) makes expanding an unset variable an error that stops the script. Consider the cleanup command rm -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.) If BACKUP_DIR is unset or empty, the command becomes rm -rf /* and starts deleting the root filesystem. Under set -u, an unset variable stops the shell with BACKUP_DIR: unbound variable before rm runs. set -u does not catch a variable that is set but empty, so write rm -rf "${BACKUP_DIR:?}"/*: the :? aborts with BACKUP_DIR: parameter null or not set when 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 pipefail changes the status of a pipeline. Normally grep ERROR app.log | wc -l reports the status of wc, the last command, so a missing app.log goes unnoticed. With pipefail, 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.

Bash · Unofficial strict mode declaration and parameter defaults
#!/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}"
done

02. 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 for awk or sed programs.
  • 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 $VAR is split on spaces, tabs and newlines, and each piece is matched as a file pattern. A file called my app.log becomes 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.

Bash · clean-cache.sh (before)
#!/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"
Terminal
shellcheck clean-cache.sh; echo "exit=$?"
Expected output (ShellCheck 0.11.0, long lines wrapped)

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=1

Read 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 local masking trap from the callout above: if find failed, the script would carry on.
  • SC2086 flags the unquoted $cache_dir: a directory called my cache would arrive as two arguments.
  • SC2115 flags rm -rf "$cache_dir"/*. If the variable were ever empty, the command would become rm -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.

Bash · clean-cache.sh (after)
#!/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"'
Terminal
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-cache
Expected output
shellcheck: 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.

Bash · Production script template with strict mode and trap cleanup
#!/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

Practice check · 3 questions

ShellCheck, variable masking and trap check

Three questions on ShellCheck severities, SC2155 and EXIT traps.

Q1. CI runs `shellcheck -S warning scripts/*.sh` and passes, yet one script breaks on a file named `my app.log` because a variable is unquoted. How did the bug get past CI?
Q2. Under `set -e`, a function runs `local sha=$(git rev-parse HEAD)` outside a Git repository. Why does the script carry on?
Q3. A script run by `sh` (Dash on Debian and Ubuntu) sets only `trap cleanup EXIT`. systemd stops it with SIGTERM. Does `cleanup` run?
Practice only: not graded, not saved, not evidence.

06. Apply it

Take one script you already use, or the health check from this skill's practice task:

  • Add set -euo pipefail on line 2 and give optional variables a default (${VAR:-default}) or a check (${VAR:?message}).
  • Register trap cleanup EXIT (plus trap 'exit 143' TERM and trap 'exit 130' INT) as soon as you create a temporary folder or lock file.
  • Run shellcheck until it prints nothing, keeping any disable comment 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

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check