Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The DEBUG trap in Bash is a specialized event handler that executes a specified command or function immediately before the shell evaluates and executes any simple command, for command, case command, select command, arithmetic for command, or the first command within a shell function.

Syntax

trap 'command_or_function' DEBUG
To remove the trap and restore default execution behavior:
trap - DEBUG

Execution Mechanics

When the DEBUG trap is triggered, the shell temporarily suspends the execution of the pending command, executes the trap handler, and then resumes execution of the pending command. Commands executed within the DEBUG trap handler itself do not trigger the DEBUG trap, preventing infinite recursive loops. During the execution of the trap handler, Bash populates the BASH_COMMAND special shell variable. This variable contains the exact command string that is about to be executed, post-alias expansion but prior to variable expansion, command substitution, or globbing.
trap 'echo "Pending execution: $BASH_COMMAND"' DEBUG

Scope and Inheritance

By default, DEBUG traps are strictly scoped to the execution environment in which they are declared. They are not inherited by shell functions, command substitutions, or subshells. To force the DEBUG trap to be inherited by functions, command substitutions, and subshells, the functrace option must be enabled:
set -o functrace

# Alternatively: set -T

Extended Debugging Behavior (extdebug)

The control flow of the shell can be directly manipulated by the DEBUG trap when the extdebug shell option is enabled. Under this mode, the exit status of the trap handler dictates how the shell handles the pending command. To enable extended debugging:
shopt -s extdebug
Once enabled, the trap handler’s return codes enforce the following behaviors:
  • Exit Status 0: The shell proceeds to execute the pending command normally.
  • Exit Status 1 (or any non-zero value except 2): The shell bypasses the execution of the pending command and proceeds to the subsequent command in the script.
  • Exit Status 2: The shell bypasses the pending command. If the shell is executing within a subroutine (a shell function or a script executed via source or .), it immediately simulates a return from that subroutine. If executing in a directly executed (non-sourced) script, it behaves identically to an exit status of 1 and merely skips the pending command without exiting the script.
shopt -s extdebug

debug_handler() {
    # Evaluate the pending command
    if [[ "$BASH_COMMAND" == *"skip_target"* ]]; then
        return 1 # Instructs Bash to skip the pending command
    fi
    return 0     # Instructs Bash to execute the pending command
}

trap debug_handler DEBUG
Master Bash with Deep Grasping Methodology!Learn More