里面的变量bash脚本变量 [英] bash script variable inside variable
问题描述
x=1
c1=string1
c2=string2
c3=string3
echo $c1
string1
我想有输出为字符串1
通过使用这样的:回声$(C($ X))
所以在剧本后,我可以递增的 X
的价值,并把它输出字符串1
,那么字符串2
和 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
它打印字符串2
;如果你想字符串1
,你需要 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屋!