I have the variable $foo="something" and would like to use:
bar="foo"; echo $($bar)
to get "something" echoed.
I have the variable $foo="something" and would like to use:
bar="foo"; echo $($bar)
to get "something" echoed.
In bash, you can use ${!variable} to use variable variables.
foo="something"
bar="foo"
echo "${!bar}"
# something
sh it says bad substitution. Any idea how to do it in sh?foo1="something1" foo2="something2" bar[0]="foo1" bar[1]="foo2" echo ${!bar[0]} echo ${!bar[1]} 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.
local -a 'keys=("${!'"$var"'[@]}")'. The indirection article on Bash Hackers goes into more depth.eval echo \"\$$bar\" would do it.
eval.sh var=$(eval echo \"\$$bar\")