Bourne Shell Building and variable reference

I have a shell that starts where the predefined env variables include:

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

I can’t change the way I get this data.

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

echo "Hello $FOO_count"

This syntax, however, is incorrect, and that is what I am looking 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

Many thanks

+3
source share
3 answers

Key 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

Cycle arithmetic is an old school - the way I write code. Modern shells have more arithmetic built-in - but the issue is noted by Bourne shell.

+2
source

You will need a evaldelayed sigil:

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

,

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

-. foo_x foos ( , $IFS, <space><tab><return>), null - :

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

unset foo_x

+1

It has been a long time since I made any Bourne shell, but have you tried the eval command?

0
source

Source: https://habr.com/ru/post/1764299/


All Articles