Below is a example BASH script.
#!/bin/bash
exithdl() {
echo "in exithdl subshell=$BASH_SUBSHELL" >&2
}
trap exithdl EXIT
fun() {
echo "in fun subshell=$BASH_SUBSHELL" >&2
trap -p EXIT >&2
echo "returned from fun"
}
echo "subshell=$BASH_SUBSHELL" >&2
trap -p EXIT >&2
echo "$(fun)" >&2
echo "exiting" >&2
When executed the following output is produced.
subshell=0
trap -- 'exithdl' EXIT
in fun subshell=1
trap -- 'exithdl' EXIT
returned from fun
exiting
in exithdl subshell=0
The trap -p EXIT >&2
command in subshells 0 and 1 shows a EXIT trap defined, but the exithdl
function only executes after subshell 0 exits. If there a way to determine that exithdl
will not execute after subshell 1 exits? In other words, is there a command or commands that I could add to fun
so this function could determine that subshell 1 does not have a EXIT trap?
In the example, an EXIT trap is defined for subshell 0, but not for subshell 1. The trap -p EXIT
command shows the exact same output when executed in both subshells. So, I have assumed trap -p EXIT
can not be used to check if a trap exists for a particular subshell. I acknowledge that the trap -p EXIT
command shows the existence of an EXIT trap when executed in fun
, but not if the EXIT trap will execute when fun returns. Am I missing something?