linux - Why trap didn't work in a pipeline -


in script have script trap.sh

#!/bin/bash trap "echo trapped" exit exit 0 

and test.sh. if test.sh like

#!/bin/bash . trap.sh 

or

#!/bin/bash ./trap.sh | : 

trap works

but if test.sh like

#!/bin/bash . trap.sh | : 

the trap didn't work.

anybody know why this?

i modified trap.sh include xtrace option.

#!/bin/bash set -x trap 'echo trapped' exit exit 0 

running trap.sh script produces

~ $ ./trap.sh | cat + trap 'echo trapped' exit + exit 0 + echo trapped trapped

sourcing first, produces

~ $ . trap.sh | cat ++ trap 'echo trapped' exit ++ exit 0 

this indicates trap executed in deeper subshell (why, don't know), , trap never executed (i confirmed in second experiment touching file int trap instead of echoing, in case there issue standard output being inherited; file never touched).

my guess somehow exit signal being ignored prior source command being executed, based on sentence description of trap command in man page:

signals ignored upon entry shell cannot trapped or reset.

as result, trap command executed, trap never registered, , not fire.


Comments