Reputation: 670
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?
Upvotes: 14
Views: 4642
Reputation: 123470
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
}
Upvotes: 13