sh loop variable and "double indirection"

Bob McGowen x4312 dept208 bob at wyse.wyse.com
Sat Feb 2 11:35:12 AEST 1991


In article <a21801wv11X.00 at amdahl.uts.amdahl.com> krs at amdahl.uts.amdahl.com (Kris Stephens [Hail Eris!]) writes:
>In article <1991Jan27.044258.18779 at shibaya.lonestar.org> 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

deleted ksh stuff

>The sh version is the same except for two parts:  delete the typeset,
>because it's not in sh, and replace   ((j = $j + 1))  with a call
>j=`expr $j + 1`  (which is the extra fork/exec).
>
>>Not very elegant since a limit of 10 iterations is hard-wired.  Can anybody
>>think of a more concise way to do this?  Using PERL is not an option, this
>>must be portable sh code.

deleted second problem


Another solution, involving only one extra fork/exec, is a small C
program to take a command line arg which is the number of iterations
needed and which prints out a character that number of times.  This
would be used in a for loop arg list with backquotes:

  for count in `iter $1`
  do
     process for $1 iterations
  done

I wrote this once but do not have the code to hand, so the following
is from memory and includes no error checking:

   #include <stdio.h>

   main(argc,argv)
   int argc;
   char **argv;
   {
      int count, iterations;

      iterations=atoi(*(argv+1));

      for(count=0; count < iterations; count++)
      {
	 putchar('a');
	 putchar(' ');  /* to separate the characters */
      }
   }

A slightly more complex version was written up in UNIXWorld, Wizard's
Grabbag.  Instead of putting out one character per iteration it
printed the integer with printf, followed by a newline.  I do not
remember the rationale given for using this method.  The mods are
left up to you if you prefer that approach.  I did just compile the
above and it works as advertised.

Note that the for loop variable will not contain anything of value,
it is just a method for looping a specific number of times.

Bob McGowan  (standard disclaimer, these are my own ...)
Product Support, Wyse Technology, San Jose, CA
..!uunet!wyse!bob
bob at wyse.com



More information about the Comp.unix.shell mailing list