How can I find the value of a shell variable whose name is the value of another shell variable?

How can I find the value of a shell variable whose name is the value of another shell variable?


Versions of Bash newer than Bash-2.0 support this directly. You can use

${!var}

For example, the following sequence of commands will echo `z':

var1=var2
var2=z
echo ${!var1}

For sh compatibility, use the `eval' builtin. The important
thing to remember is that `eval' expands the arguments you give
it again, so you need to quote the parts of the arguments that
you want `eval' to act on.

For example, this expression prints the value of the last positional
parameter:

eval echo \"\$\{$#\}\"

The expansion of the quoted portions of this expression will be
deferred until `eval' runs, while the `$#' will be expanded
before `eval' is executed. In versions of bash later than bash-2.0,

echo ${!#}

does the same thing.

This is not the same thing as ksh93 `nameref' variables, though the syntax
is similar. I may add namerefs in a future bash version.



Home FAQ