Question

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?

Was it helpful?

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
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top