Search code examples
shdash-shell

Print variables with number of iteration index in dash


I work in dash and I would like to know if there is any method to print variable with index of number of iteration.

CODE :

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

Thank you!


Solution

  • In POSIX sh, you need to use eval to perform indirect expansion:

    eval "result=\$var$tmp"
    

    Note that there are much better ways to do this in ksh, bash or other shells; see BashFAQ #6 for a comprehensive discussion of both indirect expansion and indirect assignment spanning all these shells.