Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: trap does not work in a trap function?



On Thu, 09 Sep 2010 10:17:33 +0200
"Dominik Vogt" <dominik.vogt@xxxxxx> wrote:
> shutdown () {
> 	echo shutdown
> 	trap - EXIT
> 	exit 77
> }
> 
> trap shutdown EXIT
> shutdown
> -- END sigtest
> 
> >   $ ./sigtest
> >   shutdown
> >   shutdown
> > 
> > Why is the shutdown function called again by exit when the EXIT
> > trap was just removed?  This looks like the trap builtin does not
> > properly work from within a trap handler.

The EXIT trap you removed was the one for the "shutdown" function.  In zsh,
EXIT is used with functions as well as scripts.

You can do what you want like this:

shutdown () {
  echo shutdown
  trap 'trap - EXIT' EXIT
  exit 77
}

unless shutdown is itself called from within a function, in which case
you're removing the EXIT trap for that.

From the documentation for the "trap" builtin:

  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.  The value of $? at the start of execu-
  tion is the exit status of the shell or the return status of the
  function exiting.  If sig is 0 or EXIT and the trap statement is
  not executed inside the body of a function, then the command arg
  is executed when the shell terminates.

-- 
Peter Stephenson <pws@xxxxxxx>            Software Engineer
Tel: +44 (0)1223 692070                   Cambridge Silicon Radio Limited
Churchill House, Cambridge Business Park, Cowley Road, Cambridge, CB4 0WZ, UK


Member of the CSR plc group of companies. CSR plc registered in England and Wales, registered number 4187346, registered office Churchill House, Cambridge Business Park, Cowley Road, Cambridge, CB4 0WZ, United Kingdom



Messages sorted by: Reverse Date, Date, Thread, Author