6

I am writing a shell script (#!/bin/sh) which has a variable VAR which contains the name of another variable FOO, which in turn is set to BAR.

FOO=BAR
VAR=FOO

I want to get the value of the variable named in VAR, so something like:

echo "${$VAR}"

But that does not seem to work. Suggestions?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • If the shell is Bash, the suggested duplicate is valid. If the shell is not Bash, then it is not an appropriate duplicate as none of the answers even mentions the alternative mechanism -- `eval`. – Jonathan Leffler Jun 16 '14 at 16:57
  • 1
    I solved it by saying: echo "${!VAR}". Thank you. – user3739584 Jun 16 '14 at 17:04
  • 1
    In which case, you must be using Bash rather than, say, Korn Shell. Being precise with the shell you are using improves your chances of getting a good answer. – Jonathan Leffler Jun 16 '14 at 17:07

1 Answers1

6

In Bash:

echo "${!VAR}"

Without Bash (though it works in Bash too):

eval echo "\${$VAR}"

Beware: eval is a very general mechanism that can run you into problems very easily. It works fine here, but be cautious about using it more generally.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278