Re: How to get an interation count from a while loop (bash)
- From: Douglas Mayne <doug@xxxxxxxxxxxxxxxxx>
- Date: Fri, 17 Nov 2006 10:17:05 -0700
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
.
- Follow-Ups:
- Re: How to get an interation count from a while loop (bash)
- From: Chris F.A. Johnson
- Re: How to get an interation count from a while loop (bash)
- References:
- Prev by Date: Re: configure
- Next by Date: Re: How to get an interation count from a while loop (bash)
- Previous by thread: Re: How to get an interation count from a while loop (bash)
- Next by thread: Re: How to get an interation count from a while loop (bash)
- Index(es):
Relevant Pages
|