2

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.

3

That's typically a case where you need eval.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.