61

I have the variable $foo="something" and would like to use:

bar="foo"; echo $($bar)

to get "something" echoed.

1
  • 3
    Please see BashFAQ/006. Also, you shouldn't try to use a dollar sign on the left side of an assignment. May 25, 2012 at 15:56

4 Answers 4

108

In bash, you can use ${!variable} to use variable variables.

foo="something"
bar="foo"
echo "${!bar}"

# something
6
  • 3
    in sh it says bad substitution. Any idea how to do it in sh? Sep 6, 2013 at 6:00
  • how does this work with arrays?
    – Edison
    Apr 14, 2014 at 21:14
  • 1
    @Edison foo1="something1" foo2="something2" bar[0]="foo1" bar[1]="foo2" echo ${!bar[0]} echo ${!bar[1]}
    – dAm2K
    Apr 14, 2014 at 23:23
  • I ended up doing something like " read -a subNames <<< $(eval "echo \${$rootName[@]}") for subName in "${subNames[@]}""
    – Edison
    Apr 15, 2014 at 1:42
  • @Edison see also my recent answer.
    – bishop
    Aug 6, 2014 at 18:13
9

The accepted answer is great. However, @Edison asked how to do the same for arrays. The trick is that you want your variable holding the "[@]", so that the array is expanded with the "!". Check out this function to dump variables:

$ function dump_variables() {
    for var in "$@"; do
        echo "$var=${!var}"
    done
}
$ STRING="Hello World"
$ ARRAY=("ab" "cd")
$ dump_variables STRING ARRAY ARRAY[@]

This outputs:

STRING=Hello World
ARRAY=ab
ARRAY[@]=ab cd

When given as just ARRAY, the first element is shown as that's what's expanded by the !. By giving the ARRAY[@] format, you get the array and all its values expanded.

2
  • Good point about handling arrays. Any idea how to get the indices of an array? The manual indicates this is normally done with ${!ARRAY[@]}, which seems to conflict with the variable indirection syntax.
    – dimo414
    Aug 28, 2014 at 5:33
  • @dimo414 Yeah, getting the keys through indirection is trickier. You'd have to pass just the name, then do the expansion in the method: local -a 'keys=("${!'"$var"'[@]}")'. The indirection article on Bash Hackers goes into more depth.
    – bishop
    Aug 28, 2014 at 13:20
9

eval echo \"\$$bar\" would do it.

2
  • 9
    Be aware of the security implications of eval. May 25, 2012 at 15:58
  • 3
    This solution has the benefit of being POSIX-compatible for non-Bash shells (for example, lightweight environments like embedded systems or Docker containers). And you can assign the value to another variable like so: sh var=$(eval echo \"\$$bar\") Feb 3, 2017 at 4:29
1

To make it more clear how to do it with arrays:

arr=( 'a' 'b' 'c' )
# construct a var assigning the string representation 
# of the variable (array) as its value:
var=arr[@]         
echo "${!var}"

Not the answer you're looking for? Browse other questions tagged or ask your own question.