在 Bash 中使用一个变量来引用另一个变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2634590/
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
Using a variable to refer to another variable in Bash
提问by user316100
x=1
c1=string1
c2=string2
c3=string3
echo $c1
string1
I'd like to have the output be string1
by using something like:
echo $(c($x))
我想string1
通过使用类似的东西来输出:
echo $(c($x))
So later in the script I can increment the value of x
and have it output string1
, then string2
and string3
.
所以稍后在脚本中,我可以增加 的值x
并将其输出string1
,然后string2
和string3
。
Can anyone point me in the right direction?
任何人都可以指出我正确的方向吗?
回答by Charles Duffy
See the Bash FAQ: How can I use variable variables (indirect variables, pointers, references) or associative arrays?
请参阅 Bash 常见问题解答:如何使用变量变量(间接变量、指针、引用)或关联数组?
To quote their example:
引用他们的例子:
realvariable=contents
ref=realvariable
echo "${!ref}" # prints the contents of the real variable
To show how this is useful for yourexample:
要展示这对您的示例有何用处:
get_c() { local tmp; tmp="c$x"; printf %s "${!tmp}"; }
x=1
c1=string1
c2=string2
c3=string3
echo "$(get_c)"
If, of course, you want to do it the Right Way and just use an array:
当然,如果您想以正确的方式进行操作并只使用数组:
c=( "string1" "string2" "string3" )
x=1
echo "${c[$x]}"
Note that these arrays are zero-indexed, so with x=1
it prints string2
; if you want string1
, you'll need x=0
.
请注意,这些数组是零索引的,因此x=1
打印string2
; 如果你愿意string1
,你会需要x=0
。
回答by ghostdog74
if you have bash 4.0, you can use associative arrays.. Or you can just use arrays. Another tool you can use is awk
如果你有 bash 4.0,你可以使用关联数组。. 或者你可以只使用数组。您可以使用的另一个工具是 awk
eg
例如
awk 'BEGIN{
c[1]="string1"
c[2]="string2"
c[3]="string3"
for(x=1;x<=3;x++){
print c[x]
}
}'
回答by Hai Vu
Try this:
尝试这个:
eval echo $c$x
Like others said, it makes more sense to use array in this case.
就像其他人说的,在这种情况下使用数组更有意义。