x=1
c1=string1
c2=string2
c3=string3
echo $c1
string1
Run Code Online (Sandbox Code Playgroud)
我希望string1通过使用以下内容来输出:
echo $(c($x))
所以稍后在脚本中我可以递增值x并输出string1,然后string2和string3.
谁能指出我正确的方向?
Cha*_*ffy 33
请参阅Bash FAQ:如何使用变量变量(间接变量,指针,引用)或关联数组?
引用他们的例子:
realvariable=contents
ref=realvariable
echo "${!ref}" # prints the contents of the real variable
Run Code Online (Sandbox Code Playgroud)
要说明这对您的示例有何用处:
get_c() { local tmp; tmp="c$x"; printf %s "${!tmp}"; }
x=1
c1=string1
c2=string2
c3=string3
echo "$(get_c)"
Run Code Online (Sandbox Code Playgroud)
当然,如果你想要正确的方式,只需使用一个数组:
c=( "string1" "string2" "string3" )
x=1
echo "${c[$x]}"
Run Code Online (Sandbox Code Playgroud)
请注意,这些数组是零索引的,所以用x=1它打印string2; 如果你愿意string1,你需要x=0.
| 归档时间: |
|
| 查看次数: |
43632 次 |
| 最近记录: |