53

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

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

to get "something" echoed.

user1165454
  • 671
  • 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

96

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

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

# something
Romain
  • 16,760
  • 6
  • 49
  • 57
dAm2K
  • 9,444
  • 4
  • 40
  • 45
9

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

Gilles 'SO- stop being evil'
  • 98,216
  • 36
  • 202
  • 244
Matt K
  • 12,873
  • 2
  • 31
  • 51
  • 8
    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
7

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
  • 34,858
  • 10
  • 96
  • 130
  • 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
  • 19,822
  • 8
  • 86
  • 102