0

I can't find my answer anywhere. The counter in my code doesn't work. Why and what to do ?

count=0;
for file1 in folder1;
do
    cat $file1 | while read line
    do
        echo $line;
        ((count++));
    done
done
echo "Count : ${count}";
YannickN.fr
  • 328
  • 2
  • 6
  • 18
  • 1
    Please add a suitable shebang (`#!/bin/bash`) and then paste your script at http://www.shellcheck.net/ and try to implement the recommendations made there. – Cyrus Oct 02 '21 at 20:01
  • @Cyrus Indeed, this site is useful. Thank you for sharing. – YannickN.fr Oct 02 '21 at 20:18

1 Answers1

1

When using a pipeline, the commands are executed in a subshell. Changes in a subshell don't propagate to the parent shell, so the counter is never incremented.

You don't need a pipeline here. Use a redirection instead:

    count=0
    while read line
    do
        echo $line;
        ((count++));
    done < "$file1"
choroba
  • 231,213
  • 25
  • 204
  • 289
  • This solution works only if there is something in the read variable, If the value in read is null, the count is 1 instead of 0. – Robin Jun 15 '22 at 03:53
  • @Robin: Did you initialize `count=0` before entering the loop? – choroba Jun 15 '22 at 06:14