Operating System - HP-UX
1748093 Members
5925 Online
108758 Solutions
New Discussion юеВ

Re: Incremental by 1 in the for loop

 
SOLVED
Go to solution
Dennis Handly
Acclaimed Contributor

Re: Increment by 1 in the for loop

>Frank: To my mind it can be done.

Though in efficient, you could fix it as:
typeset -i count
for i in $(< $TMPFILE); do
    print $count
    (( count+=1 ))
done

James R. Ferguson
Acclaimed Contributor

Re: Incremental by 1 in the for loop

Hi (again):

As an encompassing remark, efficiency may not seem very measureable in small scripts operating on minute amounts of data. Good practices there, however, lead to fast, scalable code that "thinks green".

Using 'typeset -i' creates an integer variable that makes arithmetic faster.

Using '(( N = N + 1 ))' to increment an integer by one lets the shell do the work without spawning a completely different process as when 'N=`expr $N + 1`' is used.

Writing 'X=$(< $FILE)' instead of 'X=$(cat $FILE)' is a subtle but faster optimization for capturing the contents of a file into a variable.

While, TMTOWTDI, there are fast and there are slow(er) paths to travel.

Regards!

...JRF...
Viktor Balogh
Honored Contributor

Re: Incremental by 1 in the for loop

just a thought:

if it would be a linux server you could just simply use the 'seq' command like this:

for i in $(seq 1000)
do
echo "This is the $i line."
done
****
Unix operates with beer.
Raynald Boucher
Super Advisor

Re: Incremental by 1 in the for loop

James,
Where can I find the documentation for the "typeset" command.

I looked in man pages, typed "typeset -?" and "-h", looked in several books but still can't find it.

RayB
James R. Ferguson
Acclaimed Contributor

Re: Incremental by 1 in the for loop

Hi (again):

> James, Where can I find the documentation for the "typeset" command.

The 'typeset' command is documented in shell manpages:

http://docs.hp.com/en/B3921-60631/sh-posix.1.html

Regards!

...JRF...

Dennis Handly
Acclaimed Contributor

Re: Incremental by 1 in the for loop

>JRF: Using '(( N = N + 1 ))' to increment an integer by one lets the shell do the work

Another reason to use ksh's (( )) is that it supports 64 bit integers and expr(1) only 32.
Arturo Galbiati
Esteemed Contributor

Re: Incremental by 1 in the for loop

Hi,
revised to be more efficient:
------------------------ CUT HERE ------------------
#!/bin/sh
# range - Generate of numbers.
typeset -i lo=$1
typeset -1 hi=$2
while [ $lo -le $hi ]
do
echo -n $lo " "
(( lo=lo+1 ))
done
------------------------ CUT HERE ------------------

HTH,
Art