TheDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
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
Execution Mechanics
When theDEBUG 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.
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:
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:
- Exit Status
0: The shell proceeds to execute the pending command normally. - Exit Status
1(or any non-zero value except2): 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 viasourceor.), it immediately simulates areturnfrom that subroutine. If executing in a directly executed (non-sourced) script, it behaves identically to an exit status of1and merely skips the pending command without exiting the script.
Master Bash with Deep Grasping Methodology!Learn More





