SUMMARY Re: sh loop variable and "double indirection"

Augustine Cano afc at shibaya.lonestar.org
Tue Feb 5 11:36:13 AEST 1991



I didn't anticipate the great response I got to my questions.  This
newsgroup is an important resource.  Many thanks to the following people,
whose summary of responses follow:

ifas730 at ccwf.cc.utexas.edu
Neil Rickert <rickert at cs.niu.edu>
bria!mike at uunet.UU.NET (Michael Stefanik)
qpliu at lyman.pppl.gov (Peter Liu)
raymond at math.berkeley.edu (Raymond Chen)
Roger Cornelius <sherpa!rac at uunet.UU.NET>
mcgrew at ichthous.Eng.Sun.COM (Darin McGrew)
...!uunet!amc.com!stuart (Stuart Poulin)
kinnersley at kuhub.cc.ukans.edu (Bill Kinnersley):



In article <1991Jan27.044258.18779 at shibaya.lonestar.org> I wrote:
>I am trying to specify (at run time) an upper limit for a loop in a shell
>script.  In pseudo-code the ideal would be something like this:
>
>read i
>for 0 to i
>do
>...
>done

Just about everybody suggested a while loop with 'expr' to increment
the loop variable.  A typical response was:

echo "enter upper limit"
read limit
i=0
while test $i -lt $limit
do
   # some processing that involves $i here
   i=`expr 1 + $i`
done

The second part of my question was the "double indirection",

>var0=REAL_VALUE0
>var1=REAL_VALUE1
>var2=REAL_VALUE2
>var3=REAL_VALUE3
>var4=REAL_VALUE4
>
>I want to manipulate variable names inside the above loop such that
>I could display the "REAL VALUEx" based on the current value of $i.

Here the solution was also unanimous: the eval command.

One solution was:

read limit
i=0
while [ $i -lt $limit ]
do
    eval echo '$'var$i
    i=`expr $i + 1`
done

"Here's an alternate way to use eval, and maybe a bit clearer."

    eval var='$'var$i
    echo $var

But there's more!  In addition to answering my specific questions,
Roger Cornelius <sherpa!rac at uunet.UU.NET> also supplied the following, which
allowed me to solve another problem I had but had not formulated in my
original posting.

"You need to add braces around a parameter when it's followed by a
letter, digit, or underscore (see Parameter Substitution in your sh
manual page).  You might want to read about eval in the sh man
page also.

x=2 y=5

while test ${x}${y} -gt 0
do
	y=`expr $y - 1`
	echo ${x}${y}
	test $y -eq 0 && x=`expr $x - 1` y=9
done

Also, ...!uunet!amc.com!stuart (Stuart Poulin) added a default value:

#Loop a default of Ulimit times.  I never start at zero as a count.

Ulimit=10
echo enter upper limit
read Ans 

i=1
while [ $i -le ${Ans:-$Ulimit} ]
do
	echo Loop Interation $i
	eval echo \$Var$i
	i=`expr $i + 1`
done
	
Again, many thanks to everyone.

-- 
Augustine Cano		INTERNET: afc at shibaya.lonestar.org
			UUCP:     ...!{ernest,egsner}!shibaya!afc



More information about the Comp.unix.shell mailing list