Bash Debugging with Trap
A DEBUG trap is a hook that runs a command before each command in a script. It lets one label mark every step inside a chosen section.
One label prints before every command
The DEBUG trap prints a fixed label before each command. The label also fires once for the trap removal command itself.
trap 'echo "before command"' DEBUG
echo "one"
echo "two"
trap - DEBUG
echo "three"A trap action can be a function
The trap calls a function that prints the label. The label prints before each echo, then once more for the removal command.
show_step() { echo "debug: next command"; }
trap show_step DEBUG
echo "alpha"
echo "beta"
trap - DEBUG
echo "gamma"The trap covers one section only
The trap is set before the calculation and removed after it. The final echo runs with no label, which proves the trap is gone.
trap 'echo "step running"' DEBUG
count=3
total=$((count * 4))
echo "total is $total"
trap - DEBUG
echo "final: $total"Example
trap 'echo "building"' DEBUG
title="Report"
lines=5
echo "$title has $lines lines"
trap - DEBUG
echo "report ready"Key points
- DEBUG trap: a hook that fires before each command runs.
- trap - DEBUG: the command that removes the DEBUG trap.
- Fixed label: plain text that never changes between runs.
- Scope: set the trap, run one section, then remove it.
- Function trap: a trap action can call a named function.
- Removal timing: the trap still fires once for its own removal command.
In this example, the DEBUG trap is set before the report section starts. It prints a fixed label before each of the three build commands. The trap is then removed, so the last echo prints with no label.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does trap - DEBUG do?