Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: Testing if there is data on stdin?



2009/9/18 Sebastian Stark <seb-zsh@xxxxxxxxxxx>:
>
> On 18.09.2009, at 01:47, Mikael Magnusson wrote:
>
>> 2009/9/18 Lloyd Zusman <ljz@xxxxxxxxxx>:
>>>
>>> Is there a way in zsh to test whether there is at least one byte of data
>>> waiting to be read from stdin without actually reading that data?
>>
>> You can either use
>> zmodload zsh/zselect
>> zselect -t0 0
>> or
>> read -t0
>
> I tried both and noticed a difference:
>
> % print foo | { cat }
> foo
> % print foo | { read -t0; cat }
> % print foo | { zmodload zsh/zselect; zselect -t0 0; cat }
> foo
>
> Can anyone explain the difference?

Yes, in the middle case, read actually does perform the read, so your
foo is in $REPLY there. When I tried it yesterday I also noticed both
zselect and read returned failure if I did something naive like echo
foo | read -t0, presumably the read is launched first in that case.
This also happens for me when I try your variants with {}, it is only
"fixed" by using () instead. But `read` swallowing your foo is the
only explanation I have, so maybe some scheduling is different for
you, since I seem to consistently get the foo output and the read
failing (for "print foo | { read -t0; cat }"). If I do this instead I
get the same result: print foo | { /bin/true; read ;t0; cat }.
% print foo | { /bin/true; read -t0; cat; echo bar $REPLY }
bar foo
% print foo | { read -t0; cat; echo bar $REPLY }
foo
bar

-- 
Mikael Magnusson



Messages sorted by: Reverse Date, Date, Thread, Author