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

Re: read command not reading from pipe. why?



Foss User ha scritto:
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?


Because the "read" is done in a child process, that starts, executes its instructions (ie: read), modifies its own private environment, and then dies, leaving the parent's environment untouched.
Try:

$echo qwerty | while read a ; do echo "a=$a" ; done
a=qwerty
$echo "a=$a"
a=


Hope that helped


Reply to: