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

Re: Testing if there is data on stdin?



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?
>
> I know I can do a [[ -t 0 ]] to see whether stdin is attached to a
> terminal, but that doesn't tell me if there is any data waiting to
> be read.
>
> The reason I want to do this is because I have a zsh script which, under
> certain circumstances, needs to get its arguments via stdin instead of
> from the command line. I'd like to be able to test within the script
> whether there is data waiting on stdin, and if so, to read it and use it
> to construct the argument list. If there is no data waiting on stdin,
> then I just want to get the arguments from the command line.
>
> Also, there is a slight difference in processing logic if I find data in
> stdin, and I need to do a little bit of special initialization _before_
> I try to read that data ... but only if that data is on stdin waiting to
> be read.
>
> Any suggestions as to how I might do this? I couldn't find anything in
> the zsh docs, but I could easily have overlooked something.
>
> Thanks in advance.

You can either use
zmodload zsh/zselect
zselect -t0 0
or
read -t0

I have a feeling the code can get pretty complicated quickly, since
both of those will return true if there's one byte of data, then you
have to recheck after each character you read so it won't suddenly
block (or use a loop of read -t -k). Unless I'm overlooking some
clever solution.

-- 
Mikael Magnusson



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