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.
RETURN trap in Bash is an event-driven mechanism that executes a specified command list whenever a shell function or a sourced script terminates. It is triggered either by an explicit return statement or by the implicit completion of the execution flow (reaching the end of the function or script block).
Syntax
Execution Mechanics
- Trigger Timing: The trap executes immediately after the function or sourced script finishes, but strictly before control is handed back to the calling environment.
- Exit Status (
$?): The exit status evaluated immediately prior to the trap’s execution is the exit status of the returning function or script. The commands executed within the trap do not alter the final return value of the function unless the trap explicitly executes a newreturncommand. - Sourced Scripts vs. Subprocesses: The trap fires when a script is executed via the
sourceor.builtins. It does not trigger when a script is executed as a standard child process (e.g.,./script.sh), as that constitutes anEXITcondition, not aRETURN.
Scope and Inheritance (functrace)
By default, the RETURN trap (along with the DEBUG trap) is not inherited by shell functions, command substitutions, or subshell environments. A RETURN trap defined in the global scope will not automatically trigger when a child function returns.
To propagate the RETURN trap to these environments, the functrace attribute must be enabled using the set builtin:
functrace is enabled, any invoked function will inherit the RETURN trap from its calling environment, causing the trap to fire upon the termination of every function in the execution tree.
Contextual Variables
When aRETURN trap is triggered, Bash preserves the execution context of the returning entity. The following internal arrays remain accessible and reflect the state of the function or script that just returned:
FUNCNAME: Contains the execution call stack.${FUNCNAME[0]}holds the name of the function that triggered the trap.BASH_SOURCE: Contains the source filenames corresponding to theFUNCNAMEstack.BASH_LINENO: Contains the line numbers in the source files where each function in the stack was invoked.
Master Bash with Deep Grasping Methodology!Learn More





