while question

Brad De Vries devriesbj at gmail.com
Tue Nov 18 13:23:48 PST 2008


On Tue, Nov 18, 2008 at 10:50 AM, idan72 <ishai at cisco.com> wrote:
>
> Hi,
>
> I try to run the following code below that contain a while statement.
> As you can see in the output it read each line in the file and echo it.
> My question is why when I exit the while loop the value of the vars yyy and
> f is undefined.
>
> Thanks
>
> cat junk.txt | while read yyy; do  echo $yyy ;export f=1 ; done ; echo
> l-$yyy; echo f=$f ;
> 444
> 555
> 333
> l-
> f=
> [ishai at mip-devtest ishai]$ cat junk.txt
> 444
> 555
> 333

I think what you're experiencing is the effects of a child shell
brought on by the pipe.  Since the pipe starts a child shell, then all
variables defined within that block are part of that child shell.
When the child shell ends, the variables all revert to their parent
shell state.

Try this as a comparison:
  while read yyy; do echo $yyy; export f=1; done < junk.txt; echo
l-$yyy; echo f=$f;

The reason this works differently is because the redirected input (<)
does not start a child shell.

HTH,
Brad.



More information about the Linux-users mailing list