views:

35

answers:

3

I have a shell that runs where the preset env variables include:

FOOCOUNT=4
FOO_0=John
FOO_1=Barry
FOO_2=Lenny
FOO_3=Samuel

I can not change the way I get this data.

I want to run a loop that generates up the variable and uses the contents.

echo "Hello $FOO_count"

This syntax is however wrong and that is what I am searching for...

count=$FOOCOUNT
counter=0
while [ $counter -lt $count ]
do
#I am looking for the syntax for: <<myContructedVar= $ + 'FOO_' + $counter>>
counter=`expr $counter + 1`
echo "Greeting #$counter: Hello, ${myContructedVar}."
done

Thanks very much

A: 

It's been a very long time since I've done any Bourne shell but have you tried the eval command?

Raj
+1  A: 

You'll need an eval and a deferred sigil:

$ foo_0=john
$ count=0    
$ name="\$foo_$count"
$ echo $name
$foo_0
$ eval echo "$name"    
john

but unless the index is truly important to you, you might use

for i in "$foo_0" "$foo_1" "$foo_2" ... ; do
...
done

and get rid of the badly named pseudo-array. And, if you have an upper bound on the number of the number of foo_x and there are no special characters in the various foos (in particular no character in $IFS which defaults to <space><tab><return>) then you can use the null-argument collapsing feature of the shell and:

$ for i in $foo_0 $foo_1 $foo_2 ; do
> echo '***' $i
> done
*** john

and allow the shell to ignore unset foo_x

msw
+1  A: 

The key is eval:

count=$FOOCOUNT
counter=0
while [ $counter -lt $count ]
do
    myConstructedVar=FOO_$counter
    counter=`expr $counter + 1`
    echo "Greeting #$counter: Hello, `eval echo \$${myConstructedVar}`."
done

The loop arithmetic is old school - the way I write the code. Modern shells have more arithmetic built in - but the question is tagged Bourne shell.

Jonathan Leffler
This is perfect. I wasn't familiar with eval but eval myVar=\$${myConstructedVar} worked perfectly.Thanks very much!
Andrei Freeman