From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: (qmail 27682 invoked by alias); 6 Aug 2012 22:49:08 -0000 Mailing-List: contact zsh-users-help@zsh.org; run by ezmlm Precedence: bulk X-No-Archive: yes List-Id: Zsh Users List List-Post: List-Help: X-Seq: 17197 Received: (qmail 25043 invoked from network); 6 Aug 2012 22:49:07 -0000 X-Spam-Checker-Version: SpamAssassin 3.3.2 (2011-06-06) on f.primenet.com.au X-Spam-Level: X-Spam-Status: No, score=-1.9 required=5.0 tests=BAYES_00 autolearn=ham version=3.3.2 Received-SPF: pass (ns1.primenet.com.au: SPF record at benizi.com designates 64.130.10.15 as permitted sender) Date: Mon, 6 Aug 2012 18:38:58 -0400 (EDT) From: "Benjamin R. Haskell" To: TjL cc: Zsh Users Subject: Re: equivalent of "if (( $+commands[FOO] ))" for functions? In-Reply-To: Message-ID: References: User-Agent: Alpine 2.01 (LNX 1266 2009-07-14) MIME-Version: 1.0 Content-Type: TEXT/PLAIN; format=flowed; charset=US-ASCII On Mon, 6 Aug 2012, TjL wrote: > I only recently learned about this method of taking some action only > if the command 'FOO' is found: > > if (( $+commands[FOO] )) > then > > # take actions > > fi > > but what I am wondering is: is there a way to have this same sort of > check, except that it also includes zsh functions/aliases? > > If yes, what's the syntax for that? if (( $+functions[FOO] )) ; then : actions here ; fi if (( $+aliases[FOO] )) ; then : actions here ; fi The $commands, $functions, and $aliases associative arrays are described in `man zshmodules` under the heading: THE ZSH/PARAMETER MODULE In case you've only seen the idiom you're using, and didn't have an explanation: $+param expands to 0 if param is unset, and 1 if it's set. The double parentheses: (( ... )) just make the conditional "mathy" (so that non-zero is true). So, you can use this with your own associative arrays, too: typeset -A some_array some_array+=( foo some-foo-thing ) if (( $+some_array[foo] )) then echo yay fi > Otherwise I'll keep using 'which' and sending the output to /dev/null > but I figured it was worth asking. Combining what you've asked about: to execute some action whether FOO is a command, an alias, or a function (or a built-in): if (( $+commands[FOO] || $+functions[FOO] || $+aliases[FOO] || $+builtins[FOO] )) then # actions fi But, since `which` is itself a shell built-in, it might be quicker and easier to just keep using it: if which FOO &> /dev/null then # actions fi I generally use (($+commands[FOO])) to test for whether a command is installed (and usually to run `alias FOO=something` if it's not). Using which FOO &> /dev/null lets the user override FOO in a different way. -- Best, Ben