6

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:

#!/bin/bash
var=$(cat -)
if [ -n "$var" ]
then
    echo "$var"
else
    echo "Pipe was empty"
fi

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

7

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.

3
  • 1
    I believe -t 0 and -N 0 are redundant.
    – Hello71
    Commented 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
    Commented 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
    Commented Apr 27, 2011 at 4:34
2

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

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .