Bash Scripting β€” Debugging Techniques

1 minute read

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:

  1. Reproduce β€” Can you trigger the bug consistently?
  2. Isolate β€” Narrow it down to the smallest failing section.
  3. Trace β€” Use set -x or echo to see actual values.
  4. Fix β€” Change one thing at a time.
  5. 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).

Updated: