Zsh Mailing List Archive
Messages sorted by:
Reverse Date,
Date,
Thread,
Author
Re: Variable expansion inside of functions
- X-seq: zsh-users 30598
- From: Aaron Schrab <aaron@xxxxxxxxxx>
- To: zsh-users@xxxxxxx
- Subject: Re: Variable expansion inside of functions
- Date: Sat, 18 Apr 2026 09:53:01 -0400
- Archived-at: <https://zsh.org/users/30598>
- Feedback-id: i1fd14616:Fastmail
- In-reply-to: <aeN6GjRBGVWDG6SP@chil>
- List-id: <zsh-users.zsh.org>
- Mail-followup-to: zsh-users@xxxxxxx
- References: <aeN6GjRBGVWDG6SP@chil>
At 13:33 +0100 18 Apr 2026, Klaus Ethgen <Klaus@xxxxxxxxx> wrote:
Here is my definition:
```
for i in pdfgrep rg
do
if whence -p "$i" >&-
then
"$i"()
{
[snip]
command "$i" "$arg[@]"
}
fi
done
```
[snip]
Is there any way to evaluate $i inside the function definition; but
only that variable?
As far as I know, there isn't a way to do that.
Are you trying to do this only in zsh, or are you looking for something
that would work in bash as well? For just zsh, unless you've unset the
FUNCTION_ARGZERO option you should be able to use "$0" for that inside
of the function definition.
Also, unless you've unset the MULTI_FUNC_DEF option you could also
eliminate the loop if not for the checking if the command exists. It
might be clearer to have the loop just build up a $cmds array (I'd call
it $commands, but zsh already defines that) of the ones that you want to
wrap and then define the functions outside the loop. I think which way
to do it is a question of taste.
And, with the default options (if SH_WORD_SPLIT isn't set) you can just
use $arg unquoted when calling the original command. You don't need the
quotes around $0 (or $i) either. Although I do tend to still quote
things to keep in the habit, since I often need to write scripts for
bash or even sh.
```
() {
local -a cmds
for i in pdfgrep rg
do
(( $+commands[$i] )) && cmds+=$i
done
$commands() {
# build $arg
command $0 $arg
}
}
```
I wrapped that in an anonymous function (which would be immediately run
and then discarded) so that $cmds could be kept local.
Messages sorted by:
Reverse Date,
Date,
Thread,
Author