Global variable in shell script

I would like to make z global variable in the following code:

 #!/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?

+4
source share
3 answers

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.

+1
source

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.

0
source

All Articles