60

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

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

to get "something" echoed.

user1165454
  • 741
  • 1
  • 6
  • 8
  • 3
    Please see [BashFAQ/006](http://mywiki.wooledge.org/BashFAQ/006). Also, you shouldn't try to use a dollar sign on the left side of an assignment. – Dennis Williamson May 25 '12 at 15:56

4 Answers4

108

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

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

# something
Romain
  • 19,910
  • 6
  • 56
  • 65
dAm2K
  • 9,923
  • 5
  • 44
  • 47
9

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

Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254
Matt K
  • 13,370
  • 2
  • 32
  • 51
  • 9
    Be aware of the [security implications of `eval`](http://mywiki.wooledge.org/BashFAQ/048). – Dennis Williamson May 25 '12 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\") ``` – Jason Suárez Feb 03 '17 at 04:29
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.

bishop
  • 37,830
  • 11
  • 104
  • 139
  • Good point about handling arrays. Any idea how to get the *indices* of an array? The [manual](http://www.gnu.org/software/bash/manual/bashref.html#Shell-Parameter-Expansion) indicates this is normally done with `${!ARRAY[@]}`, which seems to conflict with the variable indirection syntax. – dimo414 Aug 28 '14 at 05: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](http://wiki.bash-hackers.org/syntax/arrays#indirection) goes into more depth. – bishop Aug 28 '14 at 13:20
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}"
Jahid
  • 21,542
  • 10
  • 90
  • 108