Bash: indirect reference to evaluate a variable value

If you want a variable to reference another variable in Bash, that is possible using a concept called indirect reference.

Below is a simple example where ‘varname’ contains the name of another variable ‘foo’.

# our variable
foo=bar

# our reference
varname=foo

# the following syntax will ERROR and DOES NOT work !!!
echo "${$varname}"
echo "${${varname}}"

# the proper way to resolve this indirect reference
$ echo "${!varname}"
bar

# another way to resolve indirect reference
$ eval echo \$$varname
bar

 

REFERENCES

tldp.org, indirect reference concept

unix.stackexchange, indirect reference question

unix.stackexchange, nested variables using eval

stackoverflow, nested variable inside variable