Bash rarely tells you why something went wrong. A variable is empty, a path has a space, a test compares text instead of numbers, and the script quietly does the wrong thing. Debugging Bash is about making the invisible visible: what values did the variables really have, which branch ran, which line failed? This lesson gives you a toolkit, from tracing to static analysis with ShellCheck, that finds most bugs before they reach production.
In simple words
- bash -n: checks a script for syntax errors without running it.
- ShellCheck: a linter that finds common Bash bugs and explains how to fix them.
- bash -x: prints each command before it runs, so you can follow what is happening.
Step 1: check the syntax with bash -n
bash -n reads a script and reports syntax errors without running anything. It is completely safe, even on a script that deletes things:
printf '#!/usr/bin/env bash\nif [[ -f /etc/hosts ]]; then\n echo "hosts found"\n\necho done\n' > broken.shbash -n broken.shecho "exit code: $?"broken.sh: line 6: syntax error: unexpected end of fileexit code: 2"Unexpected end of file" almost always means a missing fi, done, esac, } or closing quote. The line number points to the end of the file, so look backwards for the block that was never closed.
Step 2: lint with ShellCheck
ShellCheck is a static analyser for shell scripts. It knows hundreds of common mistakes and explains each one with a code you can look up. Install it with apt install shellcheck, brew install shellcheck, or run it in a container; every serious Bash project runs it in CI.
Here is a script with several classic bugs:
printf '#!/usr/bin/env bash\nsrc=$1\ncd /backup\ncp $src /backup/\nfor f in $(ls *.log); do\n echo `date` $f\ndone\ncat /etc/hosts | grep web\nread name\n' > buggy.shcat buggy.shshellcheck buggy.shIn buggy.sh line 3:cd /backup^--------^ SC2164 (warning): Use 'cd ... || exit' or 'cd ... || return' in case cd fails.Did you mean:cd /backup || exitIn buggy.sh line 4:cp $src /backup/ ^--^ SC2086 (info): Double quote to prevent globbing and word splitting.Did you mean:cp "$src" /backup/In buggy.sh line 5:for f in $(ls *.log); do ^---------^ SC2045 (error): Iterating over ls output is fragile. Use globs.In buggy.sh line 6: echo `date` $f ^----^ SC2006 (style): Use $(...) notation instead of legacy backticks `...`. ^^ SC2086 (info): Double quote to prevent globbing and word splitting....Every message is a bug from earlier lessons:
| Code | Problem | Fix |
|---|---|---|
| SC2086 | unquoted variable | "$var" |
| SC2046 | unquoted $(command) | "$(command)" |
| SC2164 | cd without a failure check | cd dir || exit 1 |
| SC2045 | looping over ls output | for f in *.log |
| SC2006 | backticks | $(command) |
| SC2002 | useless cat | grep web /etc/hosts |
| SC2162 | read without -r | read -r name |
| SC2155 | local x=$(cmd) hides failures | declare and assign separately |
Fix them and run it again. ShellCheck prints nothing and exits 0 when a file is clean:
printf '#!/usr/bin/env bash\nset -euo pipefail\nsrc=${1:?usage: $0 FILE}\ncd /backup || exit 1\ncp -- "$src" /backup/\nfor f in ./*.log; do\n echo "$(date) $f"\ndone\ngrep web /etc/hosts\nread -r name\n' > fixed.shshellcheck fixed.shecho "exit code: $?"exit code: 0Living with ShellCheck
- Read the wiki page for any code you do not understand:
https://www.shellcheck.net/wiki/SC2086. - If a warning is truly a false positive, silence that one line with a comment that explains why, directly above it:
# shellcheck disable=SC2086 # $flags is intentionally split into several optionsdocker run $flags "$image"- Add it to CI so no unchecked script is merged:
shellcheck scripts/*.sh. - Use
-f gccfor compact one-line-per-issue output that editors and CI annotations understand.
Step 3: trace execution with bash -x
When the syntax is fine and ShellCheck is happy but the result is still wrong, watch the script run. -x (xtrace) prints every command after expansion, prefixed with +, so you see the real values:
printf '#!/usr/bin/env bash\nenv=${1:-staging}\nreplicas=2\nif [[ $env == prod ]]; then\n replicas=4\nfi\necho "deploying $replicas replicas to $env"\n' > scale.shbash -x scale.sh prod+ env=prod+ replicas=2+ [[ prod == prod ]]+ replicas=4+ echo 'deploying 4 replicas to prod'deploying 4 replicas to prodYou can see which branch ran and exactly what each variable contained. Commands inside $( ) show an extra + for each level of nesting.
Trace output goes to stderr, so it does not mix into a file you redirect stdout to. Save it separately with bash -x script.sh 2> trace.log.
Tracing only part of a script
Tracing a long script produces a lot of output. Turn it on and off around the suspicious section:
set -x# … the part you want to watch …set +xOr enable it from outside, without editing the script, with an environment variable the script checks:
[[ ${DEBUG:-0} == 1 ]] && set -xThen run DEBUG=1 ./deploy.sh.
A better trace prompt: PS4
The + prefix comes from the PS4 variable. Make it show the file, line number and function, which is invaluable in long scripts:
export PS4='+ ${BASH_SOURCE##*/}:${LINENO}:${FUNCNAME[0]:-main}: '+ deploy.sh:12:validate: [[ prod == prod ]]+ deploy.sh:31:main: kubectl apply -f deploy.yamlStep 4: print what you need
Sometimes a few well-placed messages beat a full trace. Print to stderr so debug output never pollutes real output, and show variables with markers so empty values and spaces are visible:
file="report final.txt"empty=""echo "file=[$file] empty=[$empty]" >&2declare -p filefile=[report final.txt] empty=[]declare -- file="report final.txt"declare -p name shows a variable exactly as Bash sees it, including arrays:
hosts=(web1 "web 2")declare -p hostsdeclare -a hosts=([0]="web1" [1]="web 2")Step 5: find where it fails
With set -e, a script that stops early can be confusing: it just exits. An ERR trap reports where:
set -Eeuo pipefailtrap 'echo "ERROR: line $LINENO: \"$BASH_COMMAND\" exited with $?" >&2' ERRERROR: line 27: "curl -fsS https://api.internal/health" exited with 22-E makes the trap also fire inside functions. $BASH_COMMAND is the command that failed and $? its exit code (curl's 22 means an HTTP error).
A debugging checklist
When a script misbehaves, work through these in order:
bash -n script.sh: does it even parse?shellcheck script.sh: fix every warning, especially SC2086.- Run it with
bash -xand read the trace from the top: does every variable hold what you expect? - Check exit codes: add
echo "rc=$?"after suspicious commands, or use anERRtrap. - Check the environment: is it running under cron, sudo or CI with a different
PATH, user or working folder? Printenv,idandpwdat the start. - Check line endings:
file script.shshould say "ASCII text", not "with CRLF line terminators". Fix withsed -i 's/\r$//' script.sh. - Reduce: copy the failing part into a tiny test script and run it alone.
Real-world scenario: the deploy that only failed in CI
A deploy script worked on every engineer's laptop and failed in the CI pipeline with [: too many arguments. Running it with bash -x in the pipeline showed:
+ '[' -n feature/new checkout ']'The branch name came from an environment variable that, in CI, held feature/new checkout with a space (a mistake in a pipeline variable). The test was written as [ -n $BRANCH ] without quotes, so the value split into two words and [ received too many arguments. On laptops the branch never had a space. ShellCheck had flagged the line with SC2086 months earlier, but nobody ran it. The fix was one pair of quotes and a shellcheck step in the pipeline, which caught four more similar bugs the same day.
Common mistakes
- Debugging by guessing instead of tracing.
bash -xshows the truth in seconds. - Printing debug output to stdout in functions whose output is captured.
- Leaving
set -xon in production scripts, which can print secrets (tokens, passwords) into logs. UseDEBUG=1style switches and keep secrets out of traces withset +xaround them. - Ignoring ShellCheck warnings because "it works": it works until the input has a space.
- Blanket
# shellcheck disableat the top of a file instead of per-line with a reason.
Practice
- Create a script with a missing
doneand find it withbash -n. - Write a script with three unquoted variables and a
cdwithout a check, runshellcheck, and fix everything until it prints nothing. - Trace
scale.shwithbash -xusingstagingandprod, and explain the difference in the traces. - Set
PS4to include the line number and trace a script again. - Use
declare -pto show the difference betweena="x y"anda=(x y).
Cheat sheet
bash -n script.sh syntax check only (safe)shellcheck script.sh lint; silent and exit 0 when cleanshellcheck -f gcc *.sh one line per issue# shellcheck disable=SC2086 silence one line, with a reasonbash -x script.sh trace every commandset -x … set +x trace a section[[ ${DEBUG:-0} == 1 ]] && set -xPS4='+ ${BASH_SOURCE}:${LINENO}: 'echo "x=[$x]" >&2 debug print, visible emptiesdeclare -p var exact value and typetrap '… $LINENO $BASH_COMMAND' ERRfile script.sh detect CRLF line endingsKey takeaways
bash -ncatches syntax errors safely; "unexpected end of file" means an unclosed block.- ShellCheck finds the classic Bash bugs before they run; keep scripts at zero warnings and run it in CI.
bash -xshows every command with its real values; improve it withPS4and limit it withset -x/set +x.- Print debug information to stderr, and use
declare -pto see values exactly. - An
ERRtrap with$LINENOand$BASH_COMMANDtells you where a strict-mode script stopped.