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

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



Att'n zsh-workers:  Possible bug noted at the very end of this reply.

On May 3,  9:56am, TJ Luoma wrote:
>
> I'm trying to come up with a function which will allow me to 'require'
> that a given command is found in $PATH, so I can put a line at the top
> of a script like this:

Wow, something did horrible things to your cut-and-paste.  I won't try
to excerpt your function here, but all leading whitespace is gone, and
no line wrapping in your paragraphs (I've reformatted the excerpts).
It looks like a bad html-to-text conversion.

> The SHLVL is intended to keep my login shell from exiting if a
> function doesn't find a required command.

More on this in a moment ...

> The : in the if/else/fi is because I wasn't sure how else to do a
> "not" for (( $+commands[$UTIL] ))

That one is simple:

      if ! (( $+commands[$UTIL] ))
or
      if (( $+commands[$UTIL] == 0 ))

> When I finished creating `require`, I found myself wondering if I had
> just reinvented a wheel that zsh already implemented some other way,

Look at the ${param:?message} expansion.

${NAME?WORD}
${NAME:?WORD}
     In the first form, if NAME is set, or in the second form if NAME
     is both set and non-null, then substitute its value; otherwise,
     print WORD and exit from the shell.  Interactive shells instead
     return to the prompt.  If WORD is omitted, then a standard message
     is printed.

The only tickler is that NAME and WORD aren't expanded in the output:

% print ${commands[$UTIL]?:No $UTIL found}
zsh: commands[$UTIL]: No $UTIL found

So your function is probably as good as anything, but if you want to
take advantage of the special behavior of :? for interactive shells you
can start with something like this:

  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).  So you may have
to play around with "eval" and quoting to get decent output in your
terminal, but for non-interactive shells growl will pop up.

-- 
Barton E. Schaefer



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