Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a shell exit trap from within a function in zsh and bash

Tags:

bash

shell

zsh

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?

like image 220
UloPe Avatar asked Apr 01 '14 18:04

UloPe


People also ask

Is Bash return better than exit in 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!

Does zsh run exit trap when exit is called?

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.

How do I use the trap command in Linux?

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:

What is the use of exit traps in bash script?

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. ...


1 Answers

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
}
like image 162
that other guy Avatar answered Oct 27 '22 15:10

that other guy