I am finding all files from / and for each file found, I am incrementing a counter. My issue is once the while loop is exited, the counter resets to zero.
i=0
find / 2> /dev/null | \
while read l
do
[ -f $l ] && echo $l
i=$(( ++i ))
done
echo $i
I am finding all files from / and for each file found, I am incrementing a counter. My issue is once the while loop is exited, the counter resets to zero.
i=0
find / 2> /dev/null | \
while read l
do
[ -f $l ] && echo $l
i=$(( ++i ))
done
echo $i
The pipe (|) spawns a subprocess to run the while loop; any changes made in the while loop (eg, modifying variables) is lost when the while loop completes (ie, the subprocess exits); if the while loop is just writing to stdout, or to a file, then the | while ... construct is 'ok' (ie, the output to stdout, or the file, does not 'disappear').
You can perform the same steps without generating a subprocess by instead using process substitution in which case the assignments made within the while loop are maintained after exiting the while loop, eg:
i=0
while read l
do
[ -f $l ] && echo $l
i=$(( ++i ))
done < <(find / 2> /dev/null) # process substitution
echo $i