I modified trap.sh
to include the xtrace
option.
#!/bin/bash
set -x
trap 'echo trapped' EXIT
exit 0
Running trap.sh
as a script produces
~ $ ./trap.sh | cat
+ trap 'echo trapped' EXIT
+ exit 0
+ echo trapped
trapped
Sourcing it first, however produces
~ $ . trap.sh | cat
++ trap 'echo trapped' EXIT
++ exit 0
This indicates that the trap
is executed in a deeper subshell (why, I don't know), and that the trap itself is never executed (I confirmed in a second experiment by touch
ing a file int he trap instead of just echoing, in case there was an issue with standard output being inherited; the file was never touched).
My guess is that somehow the EXIT
signal is being ignored prior to the source
command being executed, based on this sentence from the description of the trap
command in the man page:
Signals ignored upon
entry to the shell cannot be trapped or reset.
As a result, the trap
command is executed, but the trap itself is never registered, and so does not fire.