Skip to content
$ lynuxpro
← Bash Scripting

LESSON 13 OF 17 · ADVANCED · 18 MIN

Debugging and linting

HOW IT WORKSFinding bugs in scripts

SC2086deploy.shhas a bugshellcheckbefore runningbash -nsyntax onlybash -xtrace each linePS4 + line no.where it failedFixquote, test, retry
1/5

Run shellcheck first: it catches unquoted variables, wrong tests and dozens of classic mistakes.

$ shellcheck deploy.sh

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: $?"
SHELLbashutf-8 · 3L
broken.sh: line 6: syntax error: unexpected end of fileexit code: 2
OUTPUTterminalutf-8 · 2L

"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.sh
SHELLbashutf-8 · 3L
In 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....
OUTPUTterminalutf-8 · 23L

Every message is a bug from earlier lessons:

CodeProblemFix
SC2086unquoted variable"$var"
SC2046unquoted $(command)"$(command)"
SC2164cd without a failure checkcd dir || exit 1
SC2045looping over ls outputfor f in *.log
SC2006backticks$(command)
SC2002useless catgrep web /etc/hosts
SC2162read without -rread -r name
SC2155local x=$(cmd) hides failuresdeclare 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: $?"
SHELLbashutf-8 · 3L
exit code: 0
OUTPUTterminalutf-8 · 1L

Living 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"
SHELLbashutf-8 · 2L
  • Add it to CI so no unchecked script is merged: shellcheck scripts/*.sh.
  • Use -f gcc for 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
SHELLbashutf-8 · 2L
+ env=prod+ replicas=2+ [[ prod == prod ]]+ replicas=4+ echo 'deploying 4 replicas to prod'deploying 4 replicas to prod
OUTPUTterminalutf-8 · 6L

You 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 +x
SHELLbashutf-8 · 3L

Or enable it from outside, without editing the script, with an environment variable the script checks:

[[ ${DEBUG:-0} == 1 ]] && set -x
SHELLbashutf-8 · 1L

Then 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}: '
SHELLbashutf-8 · 1L
+ deploy.sh:12:validate: [[ prod == prod ]]+ deploy.sh:31:main: kubectl apply -f deploy.yaml
OUTPUTterminalutf-8 · 2L

Step 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 file
SHELLbashutf-8 · 4L
file=[report final.txt] empty=[]declare -- file="report final.txt"
OUTPUTterminalutf-8 · 2L

declare -p name shows a variable exactly as Bash sees it, including arrays:

hosts=(web1 "web 2")declare -p hosts
SHELLbashutf-8 · 2L
declare -a hosts=([0]="web1" [1]="web 2")
OUTPUTterminalutf-8 · 1L

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' ERR
SHELLbashutf-8 · 2L
ERROR: line 27: "curl -fsS https://api.internal/health" exited with 22
OUTPUTterminalutf-8 · 1L

-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:

  1. bash -n script.sh: does it even parse?
  2. shellcheck script.sh: fix every warning, especially SC2086.
  3. Run it with bash -x and read the trace from the top: does every variable hold what you expect?
  4. Check exit codes: add echo "rc=$?" after suspicious commands, or use an ERR trap.
  5. Check the environment: is it running under cron, sudo or CI with a different PATH, user or working folder? Print env, id and pwd at the start.
  6. Check line endings: file script.sh should say "ASCII text", not "with CRLF line terminators". Fix with sed -i 's/\r$//' script.sh.
  7. 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 ']'
OUTPUTterminalutf-8 · 1L

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 -x shows the truth in seconds.
  • Printing debug output to stdout in functions whose output is captured.
  • Leaving set -x on in production scripts, which can print secrets (tokens, passwords) into logs. Use DEBUG=1 style switches and keep secrets out of traces with set +x around them.
  • Ignoring ShellCheck warnings because "it works": it works until the input has a space.
  • Blanket # shellcheck disable at the top of a file instead of per-line with a reason.

Practice

  1. Create a script with a missing done and find it with bash -n.
  2. Write a script with three unquoted variables and a cd without a check, run shellcheck, and fix everything until it prints nothing.
  3. Trace scale.sh with bash -x using staging and prod, and explain the difference in the traces.
  4. Set PS4 to include the line number and trace a script again.
  5. Use declare -p to show the difference between a="x y" and a=(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 endings
OUTPUTterminalutf-8 · 12L

Key takeaways

  • bash -n catches 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 -x shows every command with its real values; improve it with PS4 and limit it with set -x / set +x.
  • Print debug information to stderr, and use declare -p to see values exactly.
  • An ERR trap with $LINENO and $BASH_COMMAND tells you where a strict-mode script stopped.