Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!sun-barr!newstop!texsun!vector!egsner!mic!ernest!shibaya!afc From: afc@shibaya.lonestar.org (Augustine Cano) Newsgroups: comp.unix.shell Subject: SUMMARY Re: sh loop variable and "double indirection" Message-ID: <1991Feb5.003613.21081@shibaya.lonestar.org> Date: 5 Feb 91 00:36:13 GMT Organization: Multidisciplinary Designs Unlimited Lines: 108 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@ccwf.cc.utexas.edu Neil Rickert bria!mike@uunet.UU.NET (Michael Stefanik) qpliu@lyman.pppl.gov (Peter Liu) raymond@math.berkeley.edu (Raymond Chen) Roger Cornelius mcgrew@ichthous.Eng.Sun.COM (Darin McGrew) ...!uunet!amc.com!stuart (Stuart Poulin) kinnersley@kuhub.cc.ukans.edu (Bill Kinnersley): In article <1991Jan27.044258.18779@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 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@shibaya.lonestar.org UUCP: ...!{ernest,egsner}!shibaya!afc