DEBUG and RETURN traps
DEBUG and RETURN are Bash pseudo-events, not operating system signals. DEBUG runs before simple commands and several other documented constructs; RETURN runs when a function or sourced script finishes. By default functions do not inherit DEBUG and RETURN traps in ordinary contexts unless traced; set -T (functrace) enables inheritance into functions, command substitutions and subshell environments. A trace can also affect program behavior; keep it small and inspect a controlled fixture. BASH_COMMAND can describe the command being executed or about to execute; do not dump it, expanded arguments or secrets into production logs. trap -p EVENT inspects configured actions, trap - EVENT restores the default. These examples intentionally use fixed labels rather than full command text. The examples use the default setting of extdebug (off). With extdebug enabled, a nonzero DEBUG action can skip the next command; tracing is not always observational.
Practical examples
Run each example as a separate script in a fresh noninteractive Bash 5.2 process and empty practice directory. Tests use C locale; do not enter expected output as code.
Trace selected commands
trap 'printf "debug\n" >&2' DEBUGprintf 'one\n'trap - DEBUGprintf 'two\n' Expected stdout:
onetwoExpected stderr:
debugdebugDEBUG fires before the first printf and before the reset command. After reset it does not fire for two.
Return tracing with functrace
work() { printf 'work\n'; }trap 'printf "returned\n" >&2' RETURNset +Tworkset -Tworktrap - RETURNworkExpected stdout:
workworkworkExpected stderr:
returnedOnly the middle invocation inherits the RETURN trap.
Inspect and reset a trap
trap ':' RETURNif [[ -n $(trap -p RETURN) ]]; then printf 'installed\n'; fitrap - RETURNif [[ -z $(trap -p RETURN) ]]; then printf 'reset\n'; fiExpected stdout:
installedresettrap -p with no action configured prints nothing for the selected event.
Common mistakes
Do not leave DEBUG traps active indefinitely or treat a trace as an exact production audit. RETURN does not mean a command failed. Do not trace credentials.
Practice
Create a short trusted function with a RETURN handler and compare calls with functrace off and on. Reset the trap and confirm later calls do not print trace messages.
Next: Debugging and testing