Skip to main content

What is the equivalent of bash indirect referencing ${!FOO} andin zsh?

Source Link
Profpatsch
  • 1.9k
  • 4
  • 21
  • 24

${!FOO} and zsh

${!FOO} performs a double substitution in bash, meaning it takes the (string) value of FOO and uses it as a variable name.
zsh doesn’t support this feature.

Is there a way to make this work the same in bash and zsh?

Background:

I’ve got a list of environment variables, like

PATH MAIL EDITOR 

and want to first print the variable names and afterwards their values.

This works in bash but not zsh:

for VAR in LIST do echo $VAR echo ${!VAR} done 

It should be somehow possible “the old way” with eval, but I can’t get it to work:

for VAR in LIST do echo $VAR echo `eval \$$VAR` done 

I’m never going to understand why I can’t simply do arbitrary deep substitutions like ${${VAR}} or even ${${${VAR}}} if need be, so an explanation for that would be nice, too.