On Tue, 28 Jun 2005 17:00:57 +0000, Levy, Chen wrote:
>
> #!/bin/bash
>
> n=5
> echo "init: $n"
>
> seq 10 | while read x ; do
>     n=$((n + 1))
>     echo -n "$$ $n : "
> done
>
> echo
> echo "after while: $n"
>
> for i in $(seq 10) ; do
>     n=$((n + 1))
>     echo -n "$$ $n : "
> done
>
> echo
> echo "after for: $n"
> echo "$$"
> ------------------------------
>
> init: 5
> 14553 6 : 14553 7 : 14553 8 : 14553 9 : 14553 10 : 14553 11 : 14553 12 : 14=
> 553=20
> 13 : 14553 14 : 14553 15 :
> after while: 5
> 14553 6 : 14553 7 : 14553 8 : 14553 9 : 14553 10 : 14553 11 : 14553 12 : 14=
> 553=20
> 13 : 14553 14 : 14553 15 :
> after for: 15
> 14553
>
> Why does the WHILE loop don't change the global $n where the FOR loop does.
> Note that in inside both loops the PID is the same.

Your `while' builtin is run in a subshell because it is piped into.

You can make it run it the current shell by replacing the piping with
an intermediate file. Change the "seq 10 | while read x ; do" to:
    seq 10 > /tmp/seq10
    exec 0< /tmp/seq10
    while read x ; do

You'll get the following:

init: 5
28037 6 : 28037 7 : 28037 8 : 28037 9 : 28037 10 : 28037 11 : 28037 12 : 28037 
13 : 28037 14 : 28037 15 :
after while: 15
28037 16 : 28037 17 : 28037 18 : 28037 19 : 28037 20 : 28037 21 : 28037 22 : 
28037 23 : 28037 24 : 28037 25 :
after for: 25
28037

Ehud.


--
 Ehud Karni           Tel: +972-3-7966-561  /"\
 Mivtach - Simon      Fax: +972-3-7966-667  \ /  ASCII Ribbon Campaign
 Insurance agencies   (USA) voice mail and   X   Against   HTML   Mail
 http://www.mvs.co.il  FAX:  1-815-5509341  / \
 GnuPG: 98EA398D <http://www.keyserver.net/>    Better Safe Than Sorry

=================================================================
To unsubscribe, send mail to [EMAIL PROTECTED] with
the word "unsubscribe" in the message body, e.g., run the command
echo unsubscribe | mail [EMAIL PROTECTED]

Reply via email to