How to tell if `stdin` buffer is not empty

I thought that bytesavailable would solve this issue (based on this), but I will demonstrate that it doesn’t work.
Say I have the following script:


Now I check how many bytes there are in a dummy file:

$ wc -c foo.txt
      21 foo.txt

So piping this file into the Julia script show display 21, I thought—but it displays zero:

$ cat foo.txt | julia test.jl

Does anyone know how to detect if anything has been passed to the script via stdin? The goal is to have something like this:

bytesavailable(stdin) > 0 ? println(read(stdin, String)) : println("No stdin given")

Thanks in advance!

how about

s = readchomp(stdin) # chomp to remove trailing \n
isempty(s) ? println("No stdin given") : println(s)


read_chomp(stdin) will block waiting for input if none is being piped in.

1 Like

Cross-pasting from Slack…

It does seem like there should be an easier (and/or more readily apparent) way to do this. Part of the complexity seems to be that the type of stdin is very dependent on how julia is started:

$ cat test.jl
using InteractiveUtils

$ julia test.jl
(Base.TTY, Base.LibuvStream, IO, Any)

$ cat /dev/null | julia test.jl
(Base.PipeEndpoint, Base.LibuvStream, IO, Any)

$ julia test.jl < /dev/null
(IOStream, IO, Any)

For the IOStream case, you could use poll_fd from the FileWatching package, but it doesn’t seem to work with Base.LibuvStream types (at least not on 1.6.0 for me).

1 Like