0

I wanted to make a quick script to count the number of lines my .scala files have:

#!/bin/bash

counter=0;
find -iname "*.scala" | while read f; do
    lc=$(cat $f | wc -l);
    counter=$((counter+lc));
    echo "$lc $counter";
done
echo "final result: $counter";

But unfortunately this prints

20 20
204 224
212 436
final result: 0

What's wrong here?

Vikas Yadav
  • 2,812
  • 1
  • 20
  • 20
devoured elysium
  • 96,110
  • 125
  • 328
  • 542

1 Answers1

3

The issue is caused because you use a pipe before your while loop.

By doing so, bash automatically creates a new subshell. All the modifications you do will be executed in the new context, and will not be propagated when the context closes.

Use process substitution instead :

#!/bin/bash

counter=0;
while read f; do
    lc=$(cat $f | wc -l);
    counter=$((counter+lc));
    echo "$lc $counter";
done < <(find -iname "*.scala")
echo "final result: $counter";
Aserre
  • 4,641
  • 4
  • 32
  • 53