unix中循环外变量的值

use*_*418 1 unix bash

请我尝试了很多选项,但我不知道如何使用循环外的值,

c='0'   
find $file -type f -maxdepth 1 -iname '*.R' -print0 | while read -d '' file; do

    c=$(($c + $(wc -l < $file) )) 

done 
echo $c
Run Code Online (Sandbox Code Playgroud)

非常感谢

anu*_*ava 6

这是因为管道在子shell中创建并处理while循环.子shell中所做的所有更改都不会反映在父shell中.

使用进程替换来避免分支子shell:

while IFS= read -d '' file; do
    c=$(($c + $(wc -l < "$file") )) 
done < <(find "$file" -type f -maxdepth 1 -iname '*.R' -print0)
Run Code Online (Sandbox Code Playgroud)