Re: [cygwin]Please why is it not working ?

From: Icarus Sparry (usenet_at_icarus.freeuk.com)
Date: 04/30/04


Date: Fri, 30 Apr 2004 05:24:25 GMT

On Wed, 28 Apr 2004 14:41:43 +0200, daniel wrote:

> Ok, I've made a "text" file which looks like this :
> Something
>
> (notice that there is a second empty line)
> now, I do :
>
> cat text | read var
>
> and then
>
> echo $var
>
> why var has no value ?

$var has no value because it is not the same var that is used in the
"read" statement. Let us assume that you are typing the commands into a
shell window, and that the process number of you current shell is 100.

Process 100 (bash) reads in a line "cat text | read var"
Process 100 (bash) sees that it needs a pipe, so it creates one.
Process 100 (bash) forks itself, to produce process 101 (bash) to run the
LHS of the pipe "cat text".
Process 100 (bash) forks itself, to produce process 102 (bash) to run the
RHS of the pipe "read var".
Process 101 (bash) sets up the arguement list, and file descriptors and
then uses the exec system call to transform itself into Process 101 (cat).
Process 102 sees that "read" is a builtin command, so it only needs to set
up the file descriptors to read from the pipe.
Process 101 (cat) copies the file to the pipe. It then has nothing more to
do so it exits.
Process 102 (bash) reads the first line from the pipe, and puts it into its
own variable called "var". It then has nothing more to do, so it exits, in
particular when it exits it releases all its memory, so its variables have
vanished.
Process 100 (bash) which was waiting for the other processes to complete, now
reads in another line "echo $var"
It sees that "echo" is a builtin, so it just runs that command. However the
variable "var" from Process 102 is nothing to do with the variable "var" in
Process 100 (In the same way that the dollar in my pocket is nothing to do with
the dollar in your pocket), so you get out nothing.

Ksh would give you a different result. Before it forks to produce the RHS of
the pipe it sees if the command is a builtin, and if so it doesn't bother
doing the fork. So Process 102 is never created, and everywhere else in the
above description you use Process 100 instead of Process 102.

For bash, you might gain more insight from

var="Original"
cat file | read var
echo $var

For what you want, try

cat file | { read var
echo $var
}

I hope this is clear



Relevant Pages