Is it possible to do a non-blocking read in bash 3.2 that is also portable to POSIX environments?
In modern versions of bash it's possible using read -r -d'' -t $TIMEOUT -N $NBYTES myvar
but I need to support bash 3.2, where -N
doesn't exist and upon timeout myvar
is not written to and the the data that was partially read is lost.
I have seen other answers that suggest using dd
with a GNU-specific iflags
argument but that won't work for me because I can't be sure that GNU dd
will be present.
Since my goal is portability I would prefer not to write this in Python, Perl, etc., but that's what I'll have to do if this is impossible.
For context, what I want to do is to run script
with its output redirected to a pipe. My bash script will read from the pipe and when any amount of data is available it'll wrap it in an envelope and output it. This will make it possible for the consumer to multiplex several streams of input. In order for it to perform well, it needs to be low-latency and also work on reasonable-size chunks of data (not 1 byte at a time).
poll
C library call to get "instantly" notified by any of a set of file descriptors having data ready. Reading in a blocking manner is not a proper way of multiplexing multiple streams into one! But this makes a lot of assumption on your system design, and I'm not quite sure where in your described system you have multiple streams, and where you blockingly want to read.