[sh] while loop and a global variable

B

blah

Guest
When I prefix [cmd=]while[/cmd] loop with pipe sh eats my global variable assigned inside the loop body
Code:
$ echo baz | while true; do foo=blah; echo $foo; break; done
blah
$ echo $foo

$
So, it's visible inside loop but not outside. Why it's invisible only when as part of a pipe?
Code:
$ while true; do foo=blah; echo $foo; break; done
blah
$ echo $foo
blah
$
In zsh it's visible in both cases.

8-CURRENT r194410M amd64 here.
 
AFAIK it's because pipes are executed in a different process.
For example, without using variables, what is your $PWD after running the following?
$ cd ~ ; cd /tmp/ | pwd
 
Loop also executes in a subshell. Try export variable to environment in plain/bourne sh. For example:
Code:
export N=1
while [ $N -lt 10 ]; do
        N=$(($N + 1))
done
echo $N
It will print 10
 
Back
Top