Skip to main content
2 of 6
How to test for data to read
Chris Davies
  • 128k
  • 16
  • 178
  • 323

[[ ! -t 0 ]] = Does standard input contains anything?

Your premise is wrong. This tests whether stdin is connected to a terminal/tty, not whether stdin contains anything.

See man test:

-t FD file descriptor FD is opened on a terminal

and man bash:

-t fd True if file descriptor fd is open and refers to a terminal.

The correct way to check if there's anything pending on stdin would be to use select(2), but that's not directly available in a shell such as bash. The closest I can suggest is to use read with an immediate timeout:

sleep 2
if read -t 0 _
then
    echo "Ready to receive data"
    read data
    echo "Received: $data"
fi

Run this and during the initial sleep, (a) try preloading stdin with some text, (b) do nothing.

Chris Davies
  • 128k
  • 16
  • 178
  • 323