0

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
Jason Aruni
  • 23
  • 1
  • 5

1 Answers1

4

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
markp-fuso
  • 28,790
  • 4
  • 16
  • 36
  • and `find / -type f` instead of `[ -f $l ]` – ufopilot May 30 '22 at 07:51
  • @ufopilot yeah but, OP's logic is keeping a count of *all* files regardless of type while only `echo`'ing the names of type `-f` files – markp-fuso May 30 '22 at 14:09
  • i see.. maybe that's what he wants – ufopilot May 30 '22 at 14:16
  • Why do these two methods give a different value of the count variable? What type of file does ```find / -type f ``` return ? – Jason Aruni May 30 '22 at 15:59
  • run the 2 `find` commands by themselves, collect (and sort) the results, then compare the results; your `find` is going to pull up 'regular' files, directories, symlinks, named pipes, etc thus leading to a larger value in `i`; the `find -type f` will only return 'regular' files and thus a smaller value in `i`; ultimately *you* need to decide what it is you're looking to `find` ('course running your `find` on the root directory is questionable, ie, why are you scanning the host's entire filesystem(s)?) – markp-fuso May 30 '22 at 16:18
  • Thank you. It now makes sense. I am testing a backup script. – Jason Aruni May 30 '22 at 16:43