2

I occured a problem and I can't find why does it run. The follow codes is both used to count the line of file 'file.in' , but the first can't change the value of $line_count

The first code is :

#!/bin/bash
line_count=0
cat file.in | while read line; do 
    let ++line_count 
done 
echo $line_count

the second code is :

#!/bin/bash
line_count=0

while read line; do 
  let ++line_count
done < file.in

echo $line_count
Dharman
  • 30,962
  • 25
  • 85
  • 135
iwantido
  • 23
  • 4

1 Answers1

1

Due to use of pipe your first code sample is executing while loop in a sub-shell hence changes made in line_count variable get lost after sub shell exits.

anubhava
  • 761,203
  • 64
  • 569
  • 643