在破折号中打印带有迭代索引数的变量

Print variables with number of iteration index in dash

我在 dash 中工作,我想知道是否有任何方法可以打印带有迭代次数索引的变量。

代码:

var1="a"
var2="b"
var3="c"

tmp=0
while [ $tmp -lt 4 ]
do
    # this is how i imagine it 
    echo $('var'$tmp)  #output should be value of var$tmp
    tmp=$((tmp+1))
done

谢谢!

在POSIX sh中,需要使用eval进行间接展开:

eval "result=$var$tmp"

请注意,在 ksh、bash 或其他 shell 中有更好的方法可以做到这一点;有关跨越所有这些 shell 的间接扩展和间接赋值的全面讨论,请参阅 BashFAQ #6

像下面这样使用eval

eval "echo \"$var${tmp}\""
# The \ escapes the $ to make it a literal dollar sign

应该在不使用第三个变量的情况下完成。

注:@Charles Duffy's 编辑时考虑了以下内容。