Bash - 变量变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10757380/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bash - variable variables
提问by user1165454
I have the variable $foo="something"
and would like to use:
我有变量$foo="something"
并想使用:
bar="foo"; echo $($bar)
to get "something" echoed.
得到“某物”的呼应。
回答by dAm2K
In bash, you can use ${!variable} to use variable variables.
在 bash 中,您可以使用 ${!variable} 来使用可变变量。
foo="something"
bar="foo"
echo "${!bar}"
回答by bishop
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:
接受的答案很棒。但是,@Edison 询问如何对数组执行相同的操作。诀窍是您希望变量包含“[@]”,以便使用“!”扩展数组。查看此函数以转储变量:
$ 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.
当以 just 形式给出时ARRAY
,第一个元素显示为!
. 通过提供ARRAY[@]
格式,您可以扩展数组及其所有值。
回答by mkb
eval echo \"\$$bar\"
would do it.
eval echo \"\$$bar\"
会做的。
回答by Jahid
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}"