【问题标题】:Create variables with dynamic index in bash在 bash 中创建具有动态索引的变量
【发布时间】:2017-03-26 18:56:15
【问题描述】:

我的代码应该可以使用 #!/bin/sh
有没有一种方法可以在循环中用迭代次数声明变量?
代码:

n=0
somestring="asdf asdf"
while [ $n -le 10 ]
do
    "var$n"="$somestring"
done

# now it is possible to call variables var0, var1, var2,...
>> echo $var2
asdf asdf   

感谢您的回答!

【问题讨论】:

  • 为什么不使用数组呢?
  • #!/bin/shAFAIK 不支持数组

标签: bash sh posix dynamic-variables


【解决方案1】:

你可以使用export

while [ $n -le 10 ]
do
    export "var$n=$somestring"
    n=$((n+1))
done

eval

while [ $n -le 10 ]
do
    eval "var$n=\"$somestring\""
    n=$((n+1))
done

【讨论】:

  • 谢谢!你甚至回答了我没有问的问题,为什么 eval 不起作用,我错过了 `\` 那里
猜你喜欢
  • 2016-01-30
  • 2013-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多