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
  • 3,094
  • 2
  • 20
  • 21
devoured elysium
  • 101,373
  • 131
  • 340
  • 557

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,916
  • 5
  • 33
  • 56