trap
is not propogated to subshells but some ways allow the subshell to report the traps of the parent shell and others don't. I did some tests on macos with bash.
GNU bash, version 4.4.12(1)-release (x86_64-apple-darwin16.3.0):
trap 'echo hello' EXIT
trap # trap -- 'echo hello' EXIT
echo "$(trap)" # trap -- 'echo hello' EXIT
trap | cat # trap -- 'echo hello' EXIT
(trap) | cat # trap -- 'echo hello' EXIT
cat < <(trap) # empty
cat <<< "$(trap)" # empty
bash -c 'trap' # empty
trap & # trap -- 'echo hello' EXIT
GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin16):
trap 'echo hello' EXIT
trap # trap -- 'echo hello' EXIT
echo "$(trap)" # trap -- 'echo hello' EXIT
trap > >(cat) # trap -- 'echo hello' EXIT
trap | cat # empty
(trap) | cat # empty
cat < <(trap) # empty
cat <<< "$(trap)" # empty
bash -c 'trap' # empty
trap & # empty
This is good to know that trap_output="$(trap)"
will work to capture trap output. I can't think of any other way to do it if that didn't work besides doing trap >trap_output_file
to output it to a file (fifo won't work in bash 3.2.57
) and then reading it back in with trap_output="$(<trap_output_file)"
fifo won't work in bash 3.2.57
because trap &
is empty for bash 3.2.57
but not bash 4.4.12
GNU bash, version 4.4.12(1)-release (x86_64-apple-darwin16.3.0):
mkfifo /tmp/fifo; trap >/tmp/fifo & trap_output=$(</tmp/fifo); rm -f /tmp/fifo; echo "$trap_output"
# trap -- 'echo hello' EXIT
mkfifo /tmp/fifo; trap_output=$(</tmp/fifo) & trap >/tmp/fifo; rm -f /tmp/fifo; echo "$trap_output"
# empty because trap_output=$(</tmp/fifo) sets the variable in a subshell
GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin16):
mkfifo /tmp/fifo; trap >/tmp/fifo & trap_output=$(</tmp/fifo); rm -f /tmp/fifo; echo "$trap_output"
# empty because trap >/tmp/fifo & is empty since it uses trap &
mkfifo /tmp/fifo; trap_output=$(</tmp/fifo) & trap >/tmp/fifo; rm -f /tmp/fifo; echo "$trap_output"
# empty because trap_output=$(</tmp/fifo) sets the variable in a subshell