如何在 bash 脚本的 for 循环中实现计数器

How to implement a counter in for loop for a bash script

我到处都找不到我的答案。我的代码中的计数器不起作用。为什么和做什么?

count=0;
for file1 in folder1;
do
    cat $file1 | while read line
    do
        echo $line;
        ((count++));
    done
done
echo "Count : ${count}";

使用管道时,命令在子shell 中执行。子 shell 中的更改不会传播到父 shell,因此计数器永远不会递增。

这里不需要管道。改用重定向:

    while read line
    do
        echo $line;
        ((count++));
    done < "$file1"