This Bash script behaves as expected.
test_this.sh
function run_this() {
trap "echo TRAPPED" EXIT
false
echo $?
}
run_this
It prints
1
TRAPPED
However, when I try to export this function, it fails to trap.
test_this2.sh
function run_this() {
trap "echo TRAPPED" EXIT
false
echo $?
}
export -f run_this
Source this at the command line and run it:
> source test_this2.sh
> run_this
Results in
1
Where did the trap go?
The
trap
is ignored when youexport
the function because when youexit
from yourlogin
shell (where the function is exported to), there is no longer ashell
to printtrapped
in. (i.e. there is never anexit
otherwise you would no longer have a shell.) When yousource test_this2.sh
, you execute it in yourlogin shell
. When the function completes, it returns to yourlogin shell
-- there is no exit. When you runtest_this.sh
, it executes in asubshell
, when thesubshell
exits, you gettrapped
printed. If you really want to see what happens when youexit
yourlogin shell
, try typingexit
and see what happens.