# [sh] while loop and a global variable



## blah (Jun 18, 2009)

When I prefix [cmd=]while[/cmd] loop with pipe sh eats my global variable assigned inside the loop body
	
	



```
$ 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?
	
	



```
$ 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.


----------



## ale (Jun 18, 2009)

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`


----------



## varda (Jun 30, 2009)

Loop also executes in a subshell. Try export variable to environment in plain/bourne sh. For example:

```
export N=1
while [ $N -lt 10 ]; do
        N=$(($N + 1))
done
echo $N
```
It will print 10


----------

