I am looking for an idiomatic pattern to use traps as a meaning "ensure" or "finally", so they should execute no matter how a bash function exits.
I've found the RETURN
trap, but nesting that is not trivial. I guess the trap inside bar shadows the trap in foo. How can I set up traps for both foo
and bar
So given the following code, I'd like to have cleanup when exiting foo
and exiting bar
.
My first attempt was to have a global string storing the cleanup tasks, but that one breaks whenever you have subshells. And it seems from the output of the following code, that RETURN signal is also "shell-global"
fooclear() { echo fooclear; }
barclear() { echo barclear; }
bar() {
echo bar
trap barclear RETURN INT ERR TERM EXIT
sleep 1
}
foo() {
echo foo
sleep 1
trap fooclear RETURN INT ERR TERM EXIT
bar
}
for i in 1 2 3; do
foo &
done
wait
And a warning: to avoid duplicate handling, one must somehow administer that a clearing function has already completed.