使用变量引用Bash中的另一个变量 [英] Using a variable to refer to another variable in Bash
问题描述
x=1
c1=string1
c2=string2
c3=string3
echo $c1
string1
我想通过使用类似以下内容来使输出为string1
:
echo $(c($x))
I'd like to have the output be string1
by using something like:
echo $(c($x))
因此,在脚本的后面,我可以增加x
的值,并使其输出string1
,然后输出string2
和string3
.
So later in the script I can increment the value of x
and have it output string1
, then string2
and string3
.
有人能指出我正确的方向吗?
Can anyone point me in the right direction?
推荐答案
请参阅Bash常见问题解答:我如何才能使用变量变量(间接变量,指针,引用)还是关联数组?
See the Bash FAQ: How can I use variable variables (indirect variables, pointers, references) or associative arrays?
举他们的例子:
realvariable=contents
ref=realvariable
echo "${!ref}" # prints the contents of the real variable
显示这对于您的示例如何有用:
To show how this is useful for your example:
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]}"
请注意,这些数组是零索引的,因此使用x=1
时,它会打印string2
;如果需要string1
,则需要x=0
.
Note that these arrays are zero-indexed, so with x=1
it prints string2
; if you want string1
, you'll need x=0
.
这篇关于使用变量引用Bash中的另一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!