Bourne Shell (/bin/sh) counting?

Rich Scott scott at SRC.Honeywell.COM
Tue Mar 20 06:17:03 AEST 1990


In article <22788 at adm.BRL.MIL> rbottin at atl.calstate.edu (Richard John Botting) writes:
>Jeff <postnews at cvbnetprime.com> Asks
>>  What is the best way to provide a loop counter in a Bourne
>>  shell script? An example script is below, all it needs is
>>  the count incrementer.
>
>>      #!/bin/sh
>>      count=0
>[...]
>>        # <increment count here>
>>       echo count=$count
> ...
>
> [ points out significant details in using 'expr' ]
> ...
>I'd like to see a neat solution (other than a "increment.c" program).

	Well, in the Korn shell, version 11/16/88 ('ksh88') or later,
you can do:

	for i in 1 2 3 4 5 6 7
        do
                ((count += 1))
                echo count = $count
        done

	
	... which gives you much the same effect. Ksh also has the 'let'
builtin, to evaluate arithmetic expresssions, and so you can do

	let count=count+1

instead, but the double parentheses construct is nice for short expressions, 
since you don't have to worry about spaces.

------------------
rich scott		        		rich at osa.com
open systems architects				scott at src.honeywell.com



More information about the Comp.unix.questions mailing list