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.

Aug 2, 2025 - 19:07
Nov 8, 2026 - 20:25
 0  95
TOPICDevOps BasicsPractical guide
How to Debug Bash Scripts: set -x, ShellCheck, traps

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.sh catches syntax errors without running anything.
  • ShellCheck finds quoting bugs, unused variables and portability problems before they reach production.
  • set -x prints each command after expansion. Set PS4 to include the file, line and function so traces are readable.
  • set -e has 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

OptionShort formWhat it doesUse it for
bash -nset -nReads commands without executing themSyntax check in CI
set -vset -o verbosePrints input lines as they are readSeeing raw source before expansion
set -xset -o xtracePrints each command after expansion, prefixed by PS4Tracing what actually ran
set -eset -o errexitExits when a command fails (with exceptions)Stopping at the first error
set -uset -o nounsetTreats unset variables as an errorCatching typos in variable names
set -o pipefailnoneA pipeline fails if any command in it failsNot hiding errors behind | tee or | grep
set -Eset -o errtraceMakes the ERR trap fire inside functions and subshellsReliable 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.

CodeProblem
SC2086Unquoted variable may split or glob
SC2046Unquoted command substitution may split
SC2155Declaring and assigning in one local or export hides the exit status
SC2164cd without a failure check
SC2034Variable 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, while or until.
  • 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

  1. 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.
  2. Print the environment the script sees: env | sort > /tmp/env.txt from inside the failing run.
  3. Cut the script down until the bug disappears, then add back the last piece.
  4. Check exit codes directly: cmd; echo "status=$?", and for pipelines echo "${PIPESTATUS[@]}".
  5. 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

SymptomLikely causeHow to confirmFix
$'\r': command not foundWindows line endingsfile script.sh shows CRLFsed -i 's/\r$//' script.sh or dos2unix
Works in terminal, fails in cronMinimal PATH and environmentLog env from cronUse full paths or set PATH at the top
Filenames with spaces break loopsUnquoted variables or for f in $(ls)ShellCheck SC2086 / SC2045Quote, and use globs or find -print0
Variable empty after a loopPipe into while runs in a subshellTrace with set -xUse while ... done < <(cmd)
Error ignored in a pipelineNo pipefailecho "${PIPESTATUS[@]}"set -o pipefail
[: too many argumentsUnquoted variable in testset -x shows the expanded wordsQuote, or use [[ ]]
Bashisms fail under shScript run by dash or POSIX shCheck the shebang and how it is calledUse #!/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

Interested in learning more?Get a callback from our training advisors.

What's Your Reaction?

Like Like 0
Dislike Dislike 0
Love Love 0
Funny Funny 0
Angry Angry 0
Sad Sad 0
Wow Wow 0
Mridul I am a passionate technology enthusiast with a strong focus on DevOps, Cloud Computing, and Cybersecurity. Through my blogs at DevOps Training Institute, I aim to simplify complex concepts and share practical insights for learners and professionals. My goal is to empower readers with knowledge, hands-on tips, and industry best practices to stay ahead in the ever-evolving world of DevOps.