dynamic variable name

I found one post in another site with a solution for my problem
the below solution should explain what I want.

 
#!/bin/sh
 
first="one"
second="two"
third="three"
 
myvar="first"
echo ${!myvar}

But this gives error 'bad substitution'

System info
SunOS sundev2 5.9 Generic_Virtual sun4u sparc SUNW,Sun-Fire-V245

Any help?

What output do you want from this line? Not possile to guess because it gives a syntax error.

the output should be

one

Ok this works in bash

#!/bin/bash

cell1="one"
cell2="two"
cell3="three"

i=1

while [ $i -lt 4 ]
do
    var_name="cell"$i
    echo ${!var_name}
    i=`expr $i + 1`
done

output

one
two
three

is it possible in sh

Second attempt. This time with the eval syntax correct. Tried with Bourne Shell, ksh and Posix Shell.

#!/bin/sh

cell1="one"
cell2="two"
cell3="three"

i=1

while [ $i -lt 4 ]
do
    var_name="cell${i}"
    eval echo \$${var_name}
    i=`expr $i + 1`
done

one
two
three
1 Like