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

Re: a 'require' function for zsh scripts and interactive functions

On Thu, 03 May 2012 08:23:29 -0700
Bart Schaefer <schaefer@xxxxxxxxxxxxxxxx> wrote:
>   require () {
>     setopt localtraps
>     for UTIL
>     do
>       trap "msg 'No $UTIL found'" EXIT
>       : ${commands[$UTIL]:?require failed}
>     done
>     trap - EXIT
>   }
> There's one more gotcha with that which may be a bug:  The EXIT trap is
> skipped when the function returns with 'require failed' (but still run
> by non-interactive shells when an actual exit occurs).

It's not entirely clear whether it's correct, since we don't explicitly
define what it should do and EXIT traps in functions are specific to
zsh, but it's plausible.  The ":?"  syntax causes immediate exit from
the shell, or back to the prompt: in other words, it's treated as an
immediate error, i.e. the same as e.g.:

% fn() { trap 'echo EXITING' EXIT; echo ${**}; }
% fn
fn: bad substitution
% fn() { trap 'echo EXITING' EXIT; echo ${foo:?nope, sorry}; }
% fn
fn: foo: nope, sorry

The cases are, however, different when you're exiting the shell:

% zsh -fc 'trap "echo EXITING" EXIT; echo ${foo:?nope, sorry}' 
zsh:1: foo: nope, sorry
% zsh -fc 'trap "echo EXITING" EXIT; echo ${**}'              
zsh:1: bad substitution

Bash calls the trap in both cases.

You can argue the function and shell cases are different since the ":?"
might be considered to cause the function to abort, with nothing more in
the main body of the script executing, but then the shell to exit
normally (apart from the status), so the EXIT trap would be run.

So there are actually 16 possibilities, though the realistic ones are
where the trap occurs additionally in one or more of the three remaining

You might well consider the most useful behaviour is for the trap
to happen in all cases, since it's there to clear up.

Peter Stephenson <p.w.stephenson@xxxxxxxxxxxx>
Web page now at http://homepage.ntlworld.com/p.w.stephenson/

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