Alex Rivera | Logout

Lookup shell variables by name, indirectly

Asked 2009-11-07T19:49:00.400
18

Let's say I have a variable's name stored in another variable:

myvar=123
varname=myvar

Now, I'd like to get 123 by just using $varname variable. Is there a direct way for that? I found no such bash builtin for lookup by name, so came up with this:

function var { v="\$$1"; eval "echo "$v; }

so

var $varname  # gives 123

Which doesn't look too bad in the end, but I'm wondering if I missed something more obvious.

Edit
Report

1 Answer

23

From the man page of bash:

${!varname}

If the first character of parameter is an exclamation point, a level of variable indirection is introduced. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself. This is known as indirect expansion.

answered 2009-11-07T19:58:54.263

Your Answer