Linux Basic — Debugging Techniques
Debugging Techniques
A robust script (last chapter) fails loudly. But when it does fail, you still have to find the bug. Bash gives you tracing, a powerful static analyser (ShellCheck), and a small set of conventions for adding diagnostics on demand.
What You Will Learn
By the end of this chapter you will be able to:
- Enable command tracing with
set -xand customise thePS4prompt - Run a one-off trace with
bash -x script.sh - Use
shellcheckto catch dozens of common bugs before they happen - Add a toggleable debug mode to your scripts
- Recognise (and avoid) the 10 most common shell-scripting bugs
Topics in This Chapter
| # | Topic | Description |
|---|---|---|
| 1 | set -x (xtrace) | enable tracing, custom PS4 |
| 2 | bash -x Flag | trace a single run from outside |
| 3 | ShellCheck | the static analyser everyone should run |
| 4 | Debug Mode | DEBUG=1 toggles + per-section trace |
| 5 | Common Scripting Bugs | the top 10 things that bite |
| 6 | Practice Exercises | Hands-on tasks |
The Debugging Mindset
Two rules to internalise:
- Make the script tell you what it’s doing. Tracing turns “this doesn’t work” into “I can see exactly where it broke.”
- Use static analysis first. ShellCheck finds 90% of bugs before you ever run the script — including bugs that only manifest in edge cases.
The single best workflow is:
shellcheck script.sh && bash -n script.sh && bash -x script.sh
shellcheck— static analysis (catches quoting bugs, unused vars, bad globs)bash -n— parse-only, no execution (catches syntax errors)bash -x— trace the actual run
Combine those three before running anything destructive.
Next → set -x (xtrace)