Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 2 down vote accepted

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.

share|improve this answer
I believe -t 0 and -N 0 are redundant. –  Hello71 Apr 27 '11 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 '11 at 4:31
if test -t 0; then echo "None"; else echo "$(cat -)"; fi Just figured out by trial and error –  MechMK1 Apr 27 '11 at 4:34

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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