odd problem in read lines from file

Hi,

I wrote a small program to read lines from a file and count the lines. The program is as below:

filename=$1
count=0    
cat $filename | while read -r line
do  
    printf "%5d:%s\n" $count "$line"
    count=$((count + 1))
done
echo " $count "

After I run the program, the result is below:

   0:This
    1:is
    2:test
    3:
    4:!
    5:
 0 

I don't understand why the count is still 0 after the read lines loop. Can someone give any advices? Thanks!

BashPitfalls - Greg's Wiki

Hi yazu,

Thanks. The information is very helpful.

This is a useless use of cat. In this case the useless cat doesn't just waste CPU time, it also prevents variables from being modified because the things after the pipe execute in a subshell. Remove the useless cat and it should work:

filename=$1
count=0    
while read -r line
do  
    printf "%5d:%s\n" $count "$line"
    count=$((count + 1))
done < $filename
echo " $count "

Hi Corona688:

Thanks!