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

Re: TRAPEXIT question



On Aug 3,  2:50pm, Greg Klanderman wrote:
} Subject: TRAPEXIT question
}
} Unfortunately, it seems that if TRAPEXIT is defined from
} within a shell function or even from a "source"d file, the exit 
} hook gets called when the function exits or sourced file finishes

Yes, this is correct.  However, how that trap behaves depends upon how
you define it.  To quote the manual:

     Note that traps defined with the `trap' builtin are slightly
     different from those defined as ``TRAP'NAL () { ... }', as the
     latter have their own function environment (line numbers, local
     variables, etc.) while the former use the environment of the
     command in which they were called.  For example,

     `trap 'print $LINENO' DEBUG'

     will print the line number of command executed after it has run,
     while

     `TRAPDEBUG() { print $LINENO; }'

     will always print the number zero.

This has an interesting side-effect in the case of the EXIT trap.  If you
use the `TRAPEXIT() { ... }' function form, then other traps set within the
trap itself have the context of the TRAPEXIT function; but if you use the
`trap "..." EXIT' form, traps set within the trap have as their context a
function that has already exited -- and as a consequence they get set in
the next context up, which can even be the top-level shell.

(I don't know if any other shell behaves this way; I know bash does *not*.
The new LOCAL_TRAPS option in 3.1.6 doesn't appear to affect it.)

Anyway, this means that either of the following forms create a function
that will install an exit trap on the calling shell:

	trip() { trap 'trap "echo trip" EXIT' EXIT }
	trip() { trap 'TRAPEXIT() { echo trip }' EXIT }

Which one you use probably depends on how hairy you want the quoting to
get.  It might be easiest to define yet another function that is the real
body of the trap, and simply call it:

	troll() { print "Who's that trip-trapping over MY bridge?" }
	trip() { trap 'trap troll EXIT' EXIT }

Now that I've answered the question ... can you tell me what's wrong with
using a .zlogout file instead?

-- 
Bart Schaefer                                 Brass Lantern Enterprises
http://www.well.com/user/barts              http://www.brasslantern.com



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