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
trapis ignored when youexportthe function because when youexitfrom yourloginshell (where the function is exported to), there is no longer ashellto printtrappedin. (i.e. there is never anexitotherwise 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 thesubshellexits, you gettrappedprinted. If you really want to see what happens when youexityourlogin shell, try typingexitand see what happens.