Bash Scripting β Debugging Techniques
Chapter 24 β Debugging Techniques
Welcome to the debugging chapter! π Every script you write will eventually misbehave β the difference between a frustrated developer and a productive one is knowing how to find the bug quickly. This chapter arms you with every tool in the Bash debugging arsenal.
What Youβll Learn
| Lesson | Topic | Key Skill |
|---|---|---|
| 01 β set -x (xtrace) | Execution tracing | Watch every command as it runs |
| 02 β bash -x Flag | Invocation-level debugging | Debug without editing the script |
| 03 β ShellCheck | Static analysis | Catch bugs before you run |
| 04 β Debug Mode | Echo tracing & debug functions | Build your own debug framework |
| 05 β Common Bugs | Bug patterns & fixes | Avoid the top 10 pitfalls |
| 06 β Exercises | Practice | Put it all together |
Why Debugging Matters
Most scripts fail silently β they donβt crash, they just produce wrong results. Consider this innocent-looking snippet:
#!/usr/bin/env bash
set -euo pipefail
filename=$1
count=$(wc -l < "$filename")
echo "Lines: $count"
Looks fine β until $1 is empty, the file doesnβt exist, or it contains spaces. Debugging tools help you see what Bash actually does versus what you think it does.
The Debugging Toolkit at a Glance
βββββββββββββββββββββββββββββββββββββββββββββββββββ
β BASH DEBUGGING TOOLKIT β
ββββββββββββββββ¬βββββββββββββββββββββββββββββββββββ€
β Runtime β set -x Β· bash -x Β· bash -v β
β Static β ShellCheck Β· bash -n β
β Custom β debug() Β· DEBUG flag β
β Defensive β set -euo pipefail β
β Logging β timestamp Β· FUNCNAME array β
ββββββββββββββββ΄βββββββββββββββββββββββββββββββββββ
Debugging Mindset
Before reaching for any tool, follow this mental checklist:
- Reproduce β Can you trigger the bug consistently?
- Isolate β Narrow it down to the smallest failing section.
- Trace β Use
set -xorechoto see actual values. - Fix β Change one thing at a time.
- Verify β Confirm the fix and check for regressions.
Quick Reference
# Trace entire script
bash -x script.sh
# Trace a specific section
set -x
# ... suspicious code ...
set +x
# Syntax check without running
bash -n script.sh
# Static analysis
shellcheck script.sh
# Custom debug function
debug() { [[ "${DEBUG:-0}" == "1" ]] && echo "[DEBUG] $*" >&2; }
Prerequisites
- Comfortable with variables, functions, and control flow (Chapters 1β23)
- A terminal with Bash 4+ installed
- Optional: ShellCheck installed locally
Letβs squash some bugs! Start with Lesson 01 β set -x (xtrace).