I want to generate a set of functions in my shell in a for loop, but I can't see how to access a variable inside the function body of the function I'm creating.

In essence, I would like the following

for f in foo ; do $f() { echo $f } ; done

to generate a function foo() { echo foo }, but instead I get foo() { echo $f }.

I've read the section on parameter expansion flags in the zsh manual, but whatever I write after $f() seems to be put verbatim into the generated function's body, so I had no luck.

Maybe this is the wrong way to do this? If not I want to know how I can expand $f inside the function when it's generated.

1 Answer 1


That's typically a case where you need eval.

$ for f (foo) eval "\$f() echo ${(qq)f}"
$ which foo
foo () {
    echo 'foo'

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .