BASH - Check if unnamed pipe is empty
By John Peck •
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"
fiThe 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
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.
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