4

I would like to make z a 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 statement always outputs "0". Why?

1
  • You could use z=$(( z + i )) or (( z += i )) to about calling out to expr Commented Oct 25, 2011 at 13:25

3 Answers 3

5

Pipes start a new subshell.

Sign up to request clarification or add additional context in comments.

1 Comment

so how can I get last value inside z ?
1

The simple way to translate

find ...  | while read ...; done

to a form without pipes is using process substitution:

while read ...; done < <(find ...)

Readability suffers somewhat.

Comments

0

I don't 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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.