Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!swrinde!elroy.jpl.nasa.gov!usc!apple!vsi1!wyse!bob From: bob@wyse.wyse.com (Bob McGowen x4312 dept208) Newsgroups: comp.unix.shell Subject: Re: sh loop variable and "double indirection" Message-ID: <3110@wyse.wyse.com> Date: 2 Feb 91 00:35:12 GMT References: <1991Jan27.044258.18779@shibaya.lonestar.org> Sender: news@wyse.wyse.com Reply-To: bob@wyse.UUCP (Bob McGowen x4312 dept208) Organization: Wyse Technology Lines: 68 In article krs@amdahl.uts.amdahl.com (Kris Stephens [Hail Eris!]) writes: >In article <1991Jan27.044258.18779@shibaya.lonestar.org> afc@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 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@wyse.com