Home > database >  How to implement a counter in for loop for a bash script [duplicate]
How to implement a counter in for loop for a bash script [duplicate]

Time:10-03

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}";

CodePudding user response:

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"
  • Related