Bash - variable variables

BashVariables

Bash Problem Overview


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

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

to get "something" echoed.

Bash Solutions


Solution 1 - Bash

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

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

# something

Solution 2 - Bash

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

Solution 3 - Bash

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.

Solution 4 - Bash

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}"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1165454View Question on Stackoverflow
Solution 1 - BashdAm2KView Answer on Stackoverflow
Solution 2 - BashMatt KView Answer on Stackoverflow
Solution 3 - BashbishopView Answer on Stackoverflow
Solution 4 - BashJahidView Answer on Stackoverflow