My problem is, I want a script which reads content from a pipe, checks if it's empty and output it if not, as seen here:

var=$(cat -)
if [ -n "$var" ]
    echo "$var"
    echo "Pipe was empty"

The problem is, cat reads from stdin, if the pipe is empty. Is there any way to prevent cat from doing that? Or is cat the wrong tool to use here?

2 Answers 2


Use read -t 0 -N 0 to detect if data is available on stdin. Use test -t 0 or tty to try to detect if a pipe is connected to stdin.

  • 1
    I believe -t 0 and -N 0 are redundant.
    – Hello71
    Apr 27, 2011 at 2:21
  • Any way to put that together in a script, because I'm not sure how to realize that. Sorry, but I don't use read very often (only read -n or read as is)
    – MechMK1
    Apr 27, 2011 at 4:31
  • if test -t 0; then echo "None"; else echo "$(cat -)"; fi Just figured out by trial and error
    – MechMK1
    Apr 27, 2011 at 4:34

test -t 0, didn't work in my case, and people here say it's "non-deterministic" or something. I like the solution of wc -c (count bytes), nice and simple. Empty input has 1 byte, whereas a single character e.g. echo "a" | wc -c gives 2

| (read line; if [ $(echo "$line" | wc -c) -gt 1 ]; then echo "$line"; fi) |

This output remains pipe-able, thanks to the brackets around read; if ... See this Q&A

  • You'll also need the option -t (timeout), otherwise read will wait for user input in case of an empty pipe.
    – Suzana
    May 27, 2015 at 0:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.