Search code examples
bashbash-trapbash-function

trap in exported function silently ignored


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?


Solution

  • The trap is ignored when you export the function because when you exit from your login shell (where the function is exported to), there is no longer a shell to print trapped in. (i.e. there is never an exit otherwise you would no longer have a shell.) When you source test_this2.sh, you execute it in your login shell. When the function completes, it returns to your login shell -- there is no exit. When you run test_this.sh, it executes in a subshell, when the subshell exits, you get trapped printed. If you really want to see what happens when you exit your login shell, try typing exit and see what happens.