Consider the following shell function:
f() {
echo "function"
trap 'echo trap; sleep 1' EXIT
}
Under bash this will print the following:
~$ f
function
~$ exit
trap
On zsh however this is the result:
~$ f
function
trap
~$ exit
This is as explained in the zshbuiltins man page:
If sig is 0 or EXIT and the trap statement is executed inside the body of a function, then the command arg is executed after the function completes.
My question: Is there a way of setting an EXIT
trap that only executes on shell exit in both bash and zsh?
It is even better than EXIT in Zsh: the Bash RETURN trap will be triggered even if you terminated the function with SIGINT. Thanks for contributing an answer to Stack Overflow!
That approach however doesn't work with zsh, which doesn't run EXIT trap if exit is called from a trap handler. It also fails to report your death-by-signal to your parent. Now, beware though that if more signals arrive while you're executing cleanup, cleanup may be run again.
The most common use of the trap command though is to trap the bash-generated psuedo-signal named EXIT. Say, for example, that you have a script that creates a temporary file. Rather than deleting it at each place where you exit your script, you just put a trap command at the start of your script that deletes the file on exit:
How "Exit Traps" Can Make Your Bash Scripts Way More Robust And Reliable 1 Keeping Services Up, No Matter What. Another scenario: Imagine you are automating some system administration task, requiring you to temporarily stop a server ... 2 Capping Expensive Resources. ... 3 Plenty Of Uses. ...
Obligatory boring and uninteresting answer:
f() {
if [ "$ZSH_VERSION" ]
then
zshexit() { echo trap; sleep 1; } # zsh specific
else
trap 'echo trap; sleep 1' EXIT # POSIX
fi
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With