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:

grep somefile.text | awk '{print $2}' | while read i
if [ i$ -gt 80 ]; then
count=`expr $count + 1`
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?

# this is testing.scr
while read i;do
[ $(expr $LOOP_COUNT % 10) -eq 0 ] && echo Count is $LOOP_COUNT
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":

# this is testing2.scr
[ $# -ne 1 ] && exit 1
[ ! -r $1 ] && exit 1
exec 5<$1
while read -u 5 i;do
[ $(expr $LOOP_COUNT % 10) -eq 0 ] && echo Count is $LOOP_COUNT
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:

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. ...
  • Re: renaming files via shell script
    ... what I meant by somefile. ... echo "in for loop" ... I get 'in script' but not 'in for loop'. ...
  • 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 ...
  • 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. ...
  • Re: Programmatically determine if find command worked?
    ... Here is my script, which is quite ... specific for my programming environment: ... echo makes find case insensitive ...