Consider case 1:
$ COUNT=0 ; while [ $COUNT -ne 3 ]; do echo $COUNT; COUNT=$(expr $COUNT + 1 );done
0
1
2
$ echo $COUNT
3
By the end of the loop COUNT
variable is 3, as expected
Consider case 2:
$ COUNT=1; find . -print0 | while IFS= read -r -d '' FILE; do echo "$FILE"; expr $COUNT + 1; COUNT=$(expr $COUNT + 1 ) ;done
.
2
./file name
3
./file
4
./a
b
5
$ echo $COUNT
1
As you can see, in this case COUNT remained the same. Why ? It can be seen that it's changing inside the while loop, but not once it's out of the loop.
What exactly I am missing here ?
In your first case, all commands executed in the same shell. The content of
COUNT
is changed.In your second case a subshell is started with piping
|
, and changes in the subshell have no effect in the current shell. But he subshell knows the variableCOUNT
and the first output is2
.