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}";
Yannick.fr
  • 168
  • 2
  • 4
  • 16
  • 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. – Yannick.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:

    while read line
    do
        echo $line;
        ((count++));
    done < "$file1"
choroba
  • 216,930
  • 22
  • 195
  • 267