Bash cat, while let and pipe lead to weird visibility

So here is my script:

count=0
cat myfile | while read line
do
    #some stuff...
    let count++
    echo $count
done
echo $count

The final output of echo prints 0 instead of the number of lines in the file, although the echo statement in the while loop prints an extra value.

The problem is with the pipeline, because with a simple while loop, the last echo statement prints the correct value. How can I make this work?

+3
source share
2 answers

In Bash, you can use process substitution and avoid a temporary file, and the variables in the loop whilewill be saved.

count=0
while read -r line  # you should almost always use -r
do
    #some stuff...
    (( count++ ))   # alternative form 
    echo $count
done < <(tac myfile)
echo $count
+4
source

. :

count=0
while read line
do
    #some stuff...
    let count++
    echo $count
done < myfile
echo $count

: tac:

count=0
# Create a random file
tmpfile=$(mktemp)
tac myfile > $tmpfile
while read line
do
    #some stuff...
    let count++
    echo $count
done < $tmpfile
# remove temp file
rm $tmpfile
echo $count
+2

Source: https://habr.com/ru/post/1776059/


All Articles