Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash indirect variable referencing

foo='abc'
bar='xyz'
var=bar

How to I get access to 'xyz' when I have var?

I've tried:

$(echo $var)

and

$(eval echo $var)

I just get bar: command not found

like image 840
benwiz Avatar asked Sep 01 '16 17:09

benwiz


1 Answers

Use bash indirect variable reference:

${!var}

And of course can be done with eval, not recommended:

eval 'echo $'"$var"

Why:

$ bar=xyz

$ var='bar;whoami'

$ eval 'echo $'"$var"
xyz
spamegg

Th command whoami is being evaluated too as part of evaluation by eval, imagine a destructive command instead of whoami.


Example:

$ bar='xyz'

$ var=bar

$ echo "${!var}"
xyz

$ eval 'echo $'"$var"
xyz
like image 124
heemayl Avatar answered Oct 04 '22 08:10

heemayl