user
user

Reputation: 7333

Lookup variable value from string in shell script

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?

Upvotes: 3

Views: 1449

Answers (2)

k107
k107

Reputation: 16440

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

Upvotes: 0

choroba
choroba

Reputation: 241848

See Parameter Expansion in bash manual:

echo ${!x}

Upvotes: 7

Related Questions