In this lesson, you will learn how to turn Bash into a self-monitoring engine by using the trap command and internal shell debug options to track execution flow in real-time.
The Debug Hook Concept
Usually, when a script runs, it happens in a "black box"—you only see the output. To see what the shell is doing while it does it, we use specialized trap signals. Specifically, the DEBUG trap allows you to execute a command before every single simple command in your script.
Think of it as placing a security camera over every line of code.
Implementing the Hook
To activate this, we use set -o functrace (to ensure the trap propagates into functions) and the trap command targeting the DEBUG signal.
#!/bin/bash
# Enable inheritance of traps into functions
set -o functrace
# This command runs before EVERY line in the script
trap 'echo "DEBUG: Currently executing: $BASH_COMMAND"' DEBUG
my_function() {
echo "Inside function"
}
x=10
my_function
When you run this script, Bash will print the content of the BASH_COMMAND variable (a built-in that stores the current command string) before every step. You will see output for the variable assignment, the function call, and even the lines inside the function itself.
Why use DEBUG?
This is significantly more powerful than simply running bash -x script.sh (the standard execution trace) because you can inject logic. For example, instead of just printing the command, you could:
- Log the state of a specific variable to a log file whenever it changes.
- Pause execution (
read) until you press Enter, allowing you to manually step through complex logic. - Check the exit status of the previous command automatically.
By hooking into the shell's internal execution loop, you move from being a user of your script to an observer of the shell’s internal decision-making process.
Key Takeaway: The DEBUG trap allows you to intercept and inspect every command the shell executes, turning your script into a transparent, self-reporting process.