0

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!

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
SevO
  • 303
  • 2
  • 11

2 Answers2

1

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.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
0

Using eval like below

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

should do it without using a third variable.

Note: @Charles Duffy's [ comment ] below is taken into consideration in the edit.

Community
  • 1
  • 1
sjsam
  • 21,411
  • 5
  • 55
  • 102
  • 1
    I'm pretty staunchly against passing `eval` more than one argument -- like `ssh`, it just concatenates those arguments with whitespace to form a single string. Better to `eval "echo \"\$var${tmp}\""` -- that way we're actually *explicit* about what's going on, and won't have surprising events when your command is more involved than `echo`. – Charles Duffy Mar 27 '17 at 17:07
  • 1
    (consider `eval printf '%s\n' "hello world"`, compared to `eval 'printf "%s\n" "hello world"'`, for a case-in-point example of why passing `eval` multiple arguments leads to confusion). – Charles Duffy Mar 27 '17 at 17:08