Shell – Standard/canonical way to test whether foregoing pipeline produced output

pipeshell-scriptzsh

The situation I have in mind has the following structure:

% some_command | [PRODUCED OUTPUT] || echo 'no output' >&2

Here [PRODUCED OUTPUT] stands for some as-yet-unspecified testing command, whose value should be true (i.e. "success") iff some_command produces any output at all.

Of course, some_command stands for an arbitrarily complex pipeline, and likewise, echo 'no output' >&2 stands for some arbitrary action to perform in case some_command produces no output.

Is there a standard test to do the job represented above by [PRODUCED OUTPUT]? grep -qm1 '.' comes close but also reports false on an input consisting of empty lines.

Unlike Check if pipe is empty and run a command on the data if it isn't I just want to discard the input if it's present, I don't need to preserve it.

Best Answer

How about using read?

$ cat /dev/null | read pointless || echo no output
no output
$ echo something | read pointless || echo no output
$ printf "\n" | read pointless || echo no output
$ printf " \n" | read pointless || echo no output
$ false | read pointless || echo no output
no output

According to the Open Group definition:

EXIT STATUS

The following exit values shall be returned:

0

Successful completion.

>0

End-of-file was detected or an error occurred.

Related Question