How to set an output shell trap from a function in zsh and bash

Consider the following shell function:

f() { echo "function" trap 'echo trap; sleep 1' EXIT } 

The following will be printed in bash:

 ~$ f function ~$ exit trap 

In zsh, however, this is the result:

 ~$ f function trap ~$ exit 

This is explained on the zshbuiltins page:

If sig is 0 or EXIT, and the trap operator is executed inside the function body, then the arg command is executed after the function completes.

My question is: is there a way to set an EXIT hook that only runs on shell output in bash and zsh?

+6
source share
1 answer

Mandatory 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 } 
+5
source

All Articles