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

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

to get "something" echoed.

share|improve this question
2  
Please see 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
up vote 50 down vote accepted

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

foo="something"
bar="foo"
echo "${!bar}"
share|improve this answer
    
Much better than my answer. – mkb May 25 '12 at 16:15
    
@mkb I didn't know eval :-) – dAm2K May 25 '12 at 22:28
    
in sh it says bad substitution. Any idea how to do it in sh? – Shiplu Mokaddim Sep 6 '13 at 6:00
    
how does this work with arrays? – Edison Apr 14 '14 at 21:14
    
@Edison foo1="something1" foo2="something2" bar[0]="foo1" bar[1]="foo2" echo ${!bar[0]} echo ${!bar[1]} – dAm2K Apr 14 '14 at 23:23

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.

share|improve this answer
    
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 '14 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 '14 at 13:20

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

share|improve this answer
5  
Be aware of the security implications of eval. – Dennis Williamson May 25 '12 at 15:58
    
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 3 '17 at 4:29

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}"
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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