How to set a shell exit trap from within a function in zsh and bash
bash, shell, zsh
Solution
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
}
Problem
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?