Here is my simplified code. ls is simplified of find command. wc is simplified for another command.
n=0
ls *.cpp | while read filename ; do
c=`wc -l $filename | awk '{print $1}'}`
n=`expr $n + $c`
done
echo "$n" #always be 0
In previous code failed, the following success
n=0
ls *.cpp > /tmp/list
while read filename ; do
c=`wc -l $filename | awk '{print $1}'}`
n=`expr $n + $c`
done < /tmp/list
echo "$n"
How to use first form and get correct answer?
Or, how to use 2nd form but without another /tmp/list file?
Maybe my problem is how to pass variable between subshell which is generated automatically
In a pipe, every process except the first one is in a subshell, so the values of
$cand$nare lost. If you want to keep the count, you should put thewhileloop first:But there’s a better way: