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
.



Relevant Pages

  • Re: Variables not passed out of WHILE
    ... that values of a string are not passed out of a WHILE ... loop. ... My script will not ECHO the value of $var at the end. ...
    (comp.unix.shell)
  • Re: renaming files via shell script
    ... what I meant by somefile. ... echo "in for loop" ... I get 'in script' but not 'in for loop'. ...
    (comp.os.linux.misc)
  • Re: How do I get this out?
    ... There are so many ways to retirve information from a database. ... I use a loop for the most of the time. ... echo $linkage; ... I've edit the script a bit and got rid of some of the complex scripts ...
    (alt.php)
  • Re: tcsh read loop
    ... > echo $line ... > Can this type of loop, that reads a complete line from a file, be done in ... You have to split this script into smaller scripts, and change STDIN. ...
    (comp.unix.shell)
  • Re: Programmatically determine if find command worked?
    ... Here is my script, which is quite ... specific for my programming environment: ... echo makes find case insensitive ...
    (comp.os.linux.misc)