sh loop variable and "double indirection"

Darin McGrew mcgrew at ichthous.Eng.Sun.COM
Tue Jan 29 05:45:22 AEST 1991


afc at shibaya.lonestar.org (Augustine Cano) writes:
>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

I'd use a while loop, as such:

	read max	# Note: there is no sanity check of $max
	counter=0
	while [ $counter -le $max ]
	do
		...
		counter=`expr $counter + 1`
	done

>The next problem is the thorny one.  Some shell variables having been
>previously set up, say:
>
>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.

You need to use the eval operator.  The first evaluation will get
the value of $i, and the second one (ie, the one caused by the
eval operator) will use that value as part of the for loop:

	eval echo \$var$i

                 Darin McGrew     "The Beginning will make all things new,
           mcgrew at Eng.Sun.COM      New life belongs to Him.
       Affiliation stated for      He hands us each new moment saying,
identification purposes only.      'My child, begin again....
				    You're free to start again.'"



More information about the Comp.unix.shell mailing list