【问题标题】:Using a variable to refer to another variable in Bash在 Bash 中使用一个变量来引用另一个变量
【发布时间】:2010-04-14 02:53:39
【问题描述】:
x=1
c1=string1
c2=string2
c3=string3

echo $c1
string1

我希望输出为string1,方法如下: echo $(c($x))

所以稍后在脚本中我可以增加x 的值并让它输出string1,然后是string2string3

谁能指出我正确的方向?

【问题讨论】:

标签: bash variables


【解决方案1】:

查看 Bash 常见问题解答: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

展示这对你的示例有何用处:

get_c() { local tmp; tmp="c$x"; printf %s "${!tmp}"; }
x=1
c1=string1
c2=string2
c3=string3
echo "$(get_c)"

当然,如果您想以正确的方式进行操作,只需use an array

c=( "string1" "string2" "string3" )
x=1
echo "${c[$x]}"

请注意,这些数组是零索引的,因此使用x=1 它会打印string2;如果你想要string1,你需要x=0

【讨论】:

  • 优秀。编辑后,它变得非常清晰,是我的首选。非常感谢您的时间和知识。
【解决方案2】:

试试这个:

eval echo \$c$x

正如其他人所说,在这种情况下使用数组更有意义。

【讨论】:

  • 在不进行适当引用的情况下使用 eval(如 printf %q)从安全角度来看是非常危险的,尤其是当您的脚本正在处理可能由恶意或不受信任的进程生成的任何数据时。 (即使是一个文件名也可以用来注入恶意内容,如果这是你循环的内容)。
【解决方案3】:

如果你有 bash 4.0,你可以使用associative arrays.。或者你可以使用arrays。您可以使用的另一个工具是 awk

例如

awk 'BEGIN{
  c[1]="string1"
  c[2]="string2"
  c[3]="string3"
  for(x=1;x<=3;x++){
    print c[x]
  }
}'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多