trap in exported function silently ignored

405 views Asked by At

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?

2

There are 2 answers

0
David C. Rankin On BEST ANSWER

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.

0
thehpi On

If you want to 'trap' leaving the function use the RETURN signal. Use the ERR signal to 'trap' errors like your 'false' call.

test_this.sh

function run_this() {
    trap "echo LEAVING" RETURN
    trap "echo ERROR" ERR
    false
    echo $?
}
export -f run_this

Load and export the function

source this_this.sh

test it

run_this

returns

ERROR
1
LEAVING

start subshell

bash

test again

run_this

returns

ERROR
1
LEAVING

So the export works fine.

PS: I'm using bash 4.3.42