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

Re: Stupid shell script question about "read"



Hi, Kevin.

I don't have a solution, but I found that interesting,
so did some experiments:

$ bash --version
bash --version
GNU bash, version 3.1.0(1)-release (i486-pc-linux-gnu)
Copyright (C) 2005 Free Software Foundation, Inc.

$ echo foo | read a; echo $a
returns empty variable
a whole lot of options on read like -t 1, -n 3 and so on don't improve
that, neither does echo -e 'foo\n\n\n' or similar things.

--

$ echo foo > temp;read a < temp; echo $a
returns foo, but creates and uses a file in between

$ mkfifo myfifo
creates a named pipe

--

terminal1$ echo foo > myfifo; read a < myfifo; echo $a
just keeps working and doesn't return,
but if I do
terminal2$ cat myfifo
in another shell, I see that foo has actually gone there,
and one moment later, the whole thing returns an empty $a

[...]

--

$ echo -e "foo\n\n" > myfifo; read -n 2 a < myfifo; echo $a
returns:
bash: myfifo: interrupted during an operating system call (translation)
and an empty $a

--

$ echo -e foo\n\n > myfifo & read -n 2 a < myfifo; echo $a
[1] 7487
bash: myfifo: Unterbrechung während des Betriebssystemaufrufs (same message)

--

$ echo foo > myfifo & sleep 1; read a < myfifo; echo $a
[3] 7492
foo

Surprise, this one works.
So far so good:
echo does not return from writing into the pipe before the pipe is not read
read does not start reading from the pipe before echo has not stopped

--

now, trying:

$ echo foo > myfifo &
[1] Done echo foo >myfifo
$ read a < myfifo
$ echo $a
this one works as well.

--

Now, using *two* shells again:

terminal1$ echo foo > myfifo
remains pending until...
terminal2$ cat myfifo
foo
returns foo while echo... on shell a returns.

--

terminal1$ echo foo > myfifo
remains pending until...
terminal2$ read a < myfifo; echo $a

returns empty line on shell b while echo... on shell a returns.

It doesn't work with
terminal1$ echo foo > myfifo &
either.

--

I don't have the in depth knowledge to interpret it,
but I find it interesting and surprising.

Best wishes, js


From:
"Kevin B. McCarty" <kmccarty@Princeton.EDU>
Could someone tell me why the following works in zsh but not in
bash/posh/dash?

benjo[3]:~% echo foo bar baz | read a b c
benjo[4]:~% echo $a $b $c
foo bar baz

If I try the same with bash (or other sh-compatible shells), the
variables $a $b and $c are unset.  From the bash man page:
>[..]
So "read" claims to read from the standard input, but it doesn't
actually seem to happen when a pipe is involved.
--
-------------------------------------------------------------------
Dr. med. Jörg M. Sigle
http://www.ql-recorder.com                        +49-5527-846-535
http://www.jsigle.com       Have a lovely day...  +49-7043-950-6864



Reply to: