bug-gnu-utils
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: bash: variables inside 'while'


From: Kalle Olavi Niemitalo
Subject: Re: bash: variables inside 'while'
Date: 01 Sep 2001 08:58:55 +0300

address@hidden (Gabriel Zachmann) writes:

>     xx=1
>     cat file |
>     while read p l
>     do
>         xx=$p
>         echo xx=$xx
>         break
>     done
>     echo xx=$xx
> 
> As output I get:
> 
>     xx=grid
>     xx=1
> 
> (the first line of my 'file' contains the word grid).
> 
> ARGH! why is the variable 'xx' reset outside the 'while' loop???

It's because of the pipe.

For example:

  REPLY=foo
  echo bar | read REPLY
  echo $REPLY

This prints "foo".  The "read REPLY" command runs in a subshell
and can't affect variables of the parent shell.

IIRC, ksh runs the last statement of a pipe in the parent shell.
But bash and ash don't.  I suppose some standard requires this.

You may be able to work around this by echoing the final value
from within the pipe and capturing it in the parent shell:

  xx=1
  xx=$(cat /etc/dictionary |
       { while read p l
         do
             xx=$p
             echo >&2 xx="$xx"
             break
         done
         echo "$xx"
       })
  echo >&2 xx="$xx"



reply via email to

[Prev in Thread] Current Thread [Next in Thread]