3

In bash, if I have:

y=10
x='y'
echo $x # prints 'y'

Now I want to get $y via $x:

echo ${$x} # error: "bad substitution"; I want to print 10

How do I lookup the variable value with name $x?

3
  • Check eval Commented Jun 6, 2012 at 17:32
  • 2
    @m0skit0 please, no eval -- it has substantial security implications, as documented at mywiki.wooledge.org/BashFAQ/048. The right way, indirect variables, is documented at mywiki.wooledge.org/BashFAQ/006 Commented Jun 6, 2012 at 17:35
  • Everything has good and bad uses. You just have to know how to use it. Commented Jun 6, 2012 at 21:51

2 Answers 2

7

See Parameter Expansion in bash manual:

echo ${!x}
Sign up to request clarification or add additional context in comments.

Comments

0

Use eval for indirect references while escaping the outer dollar sign

eval echo "\${$x}"

To assign to a variable

eval "z=\${$x}"
echo "$z"
# 10

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.