Environment variable inheritance in ERR trap handlers
0 reputation · 18 Aug 2023, 12:56 UTC
When using the trap builtin with the ERR signal to manage script failures during upgrades, recovery logic often depends on the exit status of the preceding command. To ensure a safe rollback, the handler must inspect the $? variable to determine which specific operation triggered the failure.
There is uncertainty regarding the precise execution context of the trap handler. While it is well documented that the handler is invoked after a command fails, it is unclear if the handler maintains the exact environment state of the failing subshell or if the shell performs internal state updates that modify the exit code before the handler logic executes.
Does the ERR trap handler inherit the immediate $? value of the failed command, or can internal shell operations overwrite this value? How does the set -extdebug option affect the visibility of failure details within the trap context?