for loops

Jonathan I. Kamens jik at athena.mit.edu
Thu Apr 4 07:30:23 AEST 1991


In article <3693 at ux.acs.umn.edu>, edh at ux.acs.umn.edu (Merlinus Ambrosius) writes:
|> In sh, I'd like to do something like a BASIC for loop.  Say I have $FILES
|> set to some number, and I'd like to go through a loop $FILES times.  Can
|> this be done in sh?

Yes.  The trick is getting from the number to that many items that you can put
into a for loop.  Something like this

	FILES=10
	for i in `jot $FILES`; do
		echo -n "*"
	done; echo ""

will print ten asterisks and then a newline, if your echo supports "-n"
and you have "jot".  If you don't have "jot", you can get it from
/help/dist on lilac.berkeley.edu.  Alternatively, you can use awk to do
the counting:

	FILES=10
	for i in `echo $FILES | awk '{for(i=0;i<$1+0;i++){print i}; exit}'`; do
		echo -n "*"
	done; echo ""

which will print the same as the loop above.

  You could also use expr and test to decrement the variable by one on each
pass through the loop and check if it's zero, but that's very inefficient
compared to the methods above, which require only one fork to set up the count
for the entire loop.

-- 
Jonathan Kamens			              USnail:
MIT Project Athena				11 Ashford Terrace
jik at Athena.MIT.EDU				Allston, MA  02134
Office: 617-253-8085			      Home: 617-782-0710



More information about the Comp.unix.shell mailing list