I would like to make z global variable in the following code:
z
#!/bin/bash z=0; find $1 -name "*.txt" | \ while read file do i=1; z=`expr $i + $z`; echo "$z"; done echo "$z";
The last instruction always displays "0". Why?
The pipes launch a new subshell.
Easy way to translate
find ... | while read ...; done
In the form without pipes, process substitution is used:
while read ...; done < <(find ...)
Readability is somewhat affected.
I do not know why this happened, but the problem is caused by the pipe.
If you do it like this
#!/bin/bash z=0; for f in `find $1 -name "*.txt"` do i=1; z=`expr $i + $z`; echo "$z"; done echo "$z";
then $ z will not be zero.