Bash Tricks: Get the Value of a Variable whose Name is Stored in Another Variable

If want to find out the value of a variable whose name is stored in another variable, you need to dereference the variable. This is how you do it.

Lets say the name of the variable is test123 and it has a value equal to 123. Also the name test123 is stored in another variable varname. To find out the value of test123, you will use the ! dereferencing operator.

@~$ test123=123
@~$ varname=test123
@~$ echo ${!varname}
123

Took me a while to figure this out.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.