Re: How to get an interation count from a while loop (bash)



On Fri, 17 Nov 2006 07:32:06 -0800, ponga wrote:

Okay, after scouring the news, my head hurts. I need some help.
I am trying to count how many times a while loop iterates. Here is the
script snippet:
#!/bin/bash

count=0
grep somefile.text | awk '{print $2}' | while read i
do
if [ i$ -gt 80 ]; then
count=`expr $count + 1`
fi
done
echo $count

exit 0
$count returns 0 because the while loop is being executed in a
sub-shell and not able to modify the parents' $count variable, as I
understand it.
I've tried this in ksh, same result.
Can someone suggest another way to do this that would not involve
rewriting the whole thing? The only solution I have is outputing $count
into a file, then once the loop is done, read the file for the value,
but thats pretty lame.
Can someone offer a suggestion?
TIA,
Ponga


#!/bin/bash
# this is testing.scr
LOOP_COUNT=0
while read i;do
[ $(expr $LOOP_COUNT % 10) -eq 0 ] && echo Count is $LOOP_COUNT
LOOP_COUNT=$(expr $LOOP_COUNT + 1)
done
echo Total Lines Read is $LOOP_COUNT

The usage for this script is

$ cat somefile.txt | ./testing.scr

If the script is to be modified to take an argument (the file to read),
then it requires the equivalent of "file open":

#!/bin/bash
# this is testing2.scr
[ $# -ne 1 ] && exit 1
[ ! -r $1 ] && exit 1
exec 5<$1
LOOP_COUNT=0
BF=0
while read -u 5 i;do
[ $(expr $LOOP_COUNT % 10) -eq 0 ] && echo Count is $LOOP_COUNT
LOOP_COUNT=$(expr $LOOP_COUNT + 1)
done
echo Total Lines Read is $LOOP_COUN

The usage for the above script is:

$ ./testing2.scr input_file


Here is a summary of bash's file handling abilities:
http://tldp.org/LDP/abs/html/io-redirection.html

--
Douglas Mayne
.