How to Debug Bash Scripts: set -x, ShellCheck, traps
Debug Bash scripts with bash -n, ShellCheck, set -x and PS4, set -euo pipefail caveats, ERR traps, logging and bats tests, plus a common-bugs table.
To debug a Bash script, check syntax with bash -n, lint it with ShellCheck, trace execution with set -x and a descriptive PS4, and fail fast with set -euo pipefail plus an ERR trap that prints the failing line. Then reproduce the bug with the smallest input, log to stderr, and add a test so it stays fixed.
This guide belongs to our Linux and scripting track, which starts with setting up RHEL 10 for the first time. It goes past the usual "add echo statements" advice and shows how each Bash debugging option behaves, where the strict-mode options surprise people, and a reusable header you can drop into automation scripts. Options were checked against the GNU Bash reference manual and the ShellCheck wiki.
Key takeaways
bash -n script.shcatches syntax errors without running anything.- ShellCheck finds quoting bugs, unused variables and portability problems before they reach production.
set -xprints each command after expansion. SetPS4to include the file, line and function so traces are readable.set -ehas documented exceptions (conditions,&&chains, some subshells). Pair it with an ERR trap rather than trusting it blindly.- Debug output goes to stderr so it does not corrupt data a script writes to stdout.
Debugging options at a glance
| Option | Short form | What it does | Use it for |
|---|---|---|---|
bash -n | set -n | Reads commands without executing them | Syntax check in CI |
set -v | set -o verbose | Prints input lines as they are read | Seeing raw source before expansion |
set -x | set -o xtrace | Prints each command after expansion, prefixed by PS4 | Tracing what actually ran |
set -e | set -o errexit | Exits when a command fails (with exceptions) | Stopping at the first error |
set -u | set -o nounset | Treats unset variables as an error | Catching typos in variable names |
set -o pipefail | none | A pipeline fails if any command in it fails | Not hiding errors behind | tee or | grep |
set -E | set -o errtrace | Makes the ERR trap fire inside functions and subshells | Reliable error reporting |
Step 1: Check syntax before running
bash -n deploy.sh && echo "syntax OK"
This catches missing fi, done or quotes. It does not catch logic errors or commands that do not exist, because nothing runs.
Step 2: Lint with ShellCheck
ShellCheck is a static analysis tool for shell scripts. Install it from your distribution (on RHEL it is in EPEL) or run the official container image.
shellcheck deploy.sh
# Without installing it locally
podman run --rm -v "$PWD:/mnt:Z" docker.io/koalaman/shellcheck:stable deploy.sh
A typical finding:
In deploy.sh line 12:
rm -rf $TARGET_DIR/*
^---------^ SC2086 (info): Double quote to prevent globbing and word splitting.
If TARGET_DIR is empty or contains a space, that line can delete the wrong files. The fix is rm -rf "${TARGET_DIR:?}"/*, where :? stops the script if the variable is empty. Each code, such as SC2086, has a wiki page that explains the problem and the fix. Run ShellCheck in CI so every pull request is checked.
| Code | Problem |
|---|---|
| SC2086 | Unquoted variable may split or glob |
| SC2046 | Unquoted command substitution may split |
| SC2155 | Declaring and assigning in one local or export hides the exit status |
| SC2164 | cd without a failure check |
| SC2034 | Variable assigned but never used (often a typo) |
Step 3: Trace execution with set -x
Run a whole script with tracing:
bash -x deploy.sh
Or trace only the part you suspect:
set -x
rsync -a "$src/" "$dest/"
set +x
The default trace prefix is + , which tells you little in a long script. Set PS4 to show where each line came from:
export PS4='+ ${BASH_SOURCE##*/}:${LINENO}:${FUNCNAME[0]:-main}: '
bash -x deploy.sh
+ deploy.sh:14:main: dest=/srv/app
+ deploy.sh:22:sync_files: rsync -a ./build/ /srv/app/
Send the trace to a separate file
Bash 4.1 and later support BASH_XTRACEFD, which sends xtrace output to a chosen file descriptor and keeps your terminal or logs clean:
exec 5>/tmp/deploy.trace
BASH_XTRACEFD=5
set -x
Be careful with tracing in CI logs: set -x prints expanded values, including tokens or passwords held in variables. Turn tracing off around secret handling with set +x, and rely on your CI system's secret masking as a second layer.
Step 4: Fail fast, and know the exceptions
A common strict header is:
set -Eeuo pipefail
It helps, but the Bash manual lists cases where set -e does not exit:
- Commands tested by
if,whileoruntil. - Any command in an
&&or||list except the last. - Commands whose status is inverted with
!. - Functions called in those contexts, where errexit is ignored inside the whole function body.
set -e
check() { false; echo "still running"; }
if check; then echo "passed"; fi # prints "still running" and "passed"
Also note local out=$(cmd) returns the status of local, not of cmd, so a failure is hidden. Declare first, then assign: local out; out=$(cmd).
With set -u, reference optional variables with a default, such as "${DEBUG:-0}", and check arguments with "${1:-}".
Step 5: Report errors with a trap
An ERR trap prints where the failure happened. With set -E it also fires inside functions.
#!/usr/bin/env bash
set -Eeuo pipefail
on_error() {
local status=$?
echo "ERROR: status $status at ${BASH_SOURCE[1]}:${BASH_LINENO[0]} running: $BASH_COMMAND" >&2
exit "$status"
}
trap on_error ERR
cleanup() { rm -rf "${tmpdir:-}"; }
trap cleanup EXIT
tmpdir=$(mktemp -d)
The EXIT trap runs on any exit, so temporary files are removed even after an error. BASH_COMMAND holds the command that was running when the trap fired.
Step 6: Log properly
Scattered echo lines work, but a small logging function is easier to switch on and off and keeps stdout clean:
log() { printf '%s [%s] %s\n' "$(date -Is)" "$1" "${*:2}" >&2; }
debug() { [[ "${DEBUG:-0}" == 1 ]] && log DEBUG "$@" || true; }
log INFO "starting deploy to $dest"
debug "files: $(ls "$src" | wc -l)"
Run DEBUG=1 ./deploy.sh to see debug lines. For scripts run by systemd or cron, send logs to the journal with logger -t deploy "message" and read them with journalctl -t deploy.
Step 7: Reproduce, isolate, test
- Reproduce with the exact inputs, environment and user. Many "works on my machine" bugs come from a different
PATH, locale or working directory under cron. - Print the environment the script sees:
env | sort > /tmp/env.txtfrom inside the failing run. - Cut the script down until the bug disappears, then add back the last piece.
- Check exit codes directly:
cmd; echo "status=$?", and for pipelinesecho "${PIPESTATUS[@]}". - Write a test so the bug stays fixed. bats-core is a TAP-compliant test framework for Bash.
# test/deploy.bats
@test "fails when TARGET_DIR is empty" {
run env TARGET_DIR= ./deploy.sh
[ "$status" -ne 0 ]
}
Common bugs and how to spot them
| Symptom | Likely cause | How to confirm | Fix |
|---|---|---|---|
$'\r': command not found | Windows line endings | file script.sh shows CRLF | sed -i 's/\r$//' script.sh or dos2unix |
| Works in terminal, fails in cron | Minimal PATH and environment | Log env from cron | Use full paths or set PATH at the top |
| Filenames with spaces break loops | Unquoted variables or for f in $(ls) | ShellCheck SC2086 / SC2045 | Quote, and use globs or find -print0 |
| Variable empty after a loop | Pipe into while runs in a subshell | Trace with set -x | Use while ... done < <(cmd) |
| Error ignored in a pipeline | No pipefail | echo "${PIPESTATUS[@]}" | set -o pipefail |
[: too many arguments | Unquoted variable in test | set -x shows the expanded words | Quote, or use [[ ]] |
| Bashisms fail under sh | Script run by dash or POSIX sh | Check the shebang and how it is called | Use #!/usr/bin/env bash and run with bash |
A reusable script header
#!/usr/bin/env bash
# Strict mode with readable traces and error reports
set -Eeuo pipefail
IFS=$'\n\t'
export PS4='+ ${BASH_SOURCE##*/}:${LINENO}:${FUNCNAME[0]:-main}: '
[[ "${TRACE:-0}" == 1 ]] && set -x
log() { printf '%s [%s] %s\n' "$(date -Is)" "$1" "${*:2}" >&2; }
trap 'log ERROR "status $? at line $LINENO: $BASH_COMMAND"' ERR
Run with TRACE=1 ./script.sh when you need a full trace. Changing IFS to newline and tab reduces word-splitting surprises, but understand it before you adopt it, because it changes how unquoted expansions split.
When Bash is the wrong tool
If a script needs complex data structures, JSON handling beyond jq, or more than a few hundred lines, consider Python. It has better error handling and testing tools. Our post on scripting languages used in DevOps compares the options, and 10 DevOps automation scripts gives practice material.
Frequently asked questions
How do I debug a Bash script line by line?
Run it with bash -x script.sh, or put set -x before the section you want to trace and set +x after it. Set PS4 to include ${LINENO} so each traced line shows its line number.
What is the difference between set -x and set -v?
set -v prints lines as Bash reads them, before expansion. set -x prints each command after variables and globs are expanded, which is usually more useful for finding bugs.
Is set -e enough to catch all errors?
No. It does not trigger in if conditions, in && and || lists except the last command, or after !. Combine it with pipefail, nounset and an ERR trap, and check critical commands explicitly.
What does ShellCheck do?
ShellCheck is a static analyser that warns about quoting errors, unsafe patterns, unused variables and portability problems. Each warning has a code such as SC2086 with a wiki page explaining the fix.
How do I check a script's syntax without running it?
Use bash -n script.sh. It parses the file and reports syntax errors without executing commands.
Why does my script work manually but fail in cron?
Cron runs with a minimal environment and PATH, and a different working directory. Log env from the cron run, use absolute paths, and set PATH at the top of the script.
How do I stop set -x from printing secrets?
Wrap secret handling in set +x and set -x, or send traces to a protected file with BASH_XTRACEFD. Also enable secret masking in your CI system.
How can I test Bash scripts automatically?
Use bats-core to write test cases that run your script and check its exit status and output, and run ShellCheck and the tests in CI on every change.
Build scripting skills with practice
Shell scripting and troubleshooting are part of our Linux administration training, taught in Kharadi, Pune and live online. To find what a running script is doing on the system, pair this guide with monitoring processes with ps, top and htop and grep, awk and sed.
References
What's Your Reaction?
Like
0
Dislike
0
Love
0
Funny
0
Angry
0
Sad
0
Wow
0