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

Re: read command not reading from pipe. why?



On 1/4/2010 1:10 PM, Foss User wrote:
I see that the read command stores input entered only on the console
into the variables. Example:

$ read a
foo
$ echo $a
foo

But when I don't enter input on the console by keyboard, but pipe it
into the standard input of read, I am unable to store the input into
the variable.

$ echo bar | read a
$ echo $a
foo

However, the help of read says this:

$ help read
read: read [-ers] [-a array] [-d delim] [-i text] [-n nchars] [-p
prompt] [-t timeout] [-u fd] [name ...]
     Read a line from the standard input and split it into fields.

So, why is it not reading the line from standard input when input is
passed to it using a pipe?




Try this:

$ echo bar > /tmp/foo;  read a < /tmp/foo; echo $a; rm /tmp/foo

That's may not be the best approach (obviously), but if you understand what's going on above, then you can use read. The problem is that each command gets its own copy of the environment, so your

$ echo $a

is echoing its *own* a, which is empty.  Don't try this, either:

$ echo bar | read a; export a
$ echo $a

Won't work.  The piped

$ echo bar

and the

read a

are still each in their own world.


Mark Allums


Reply to: