Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

In my script, I am using the ifne utility from the moreutils package. The line can be simplified to the following:

printf "asdf\n" | ifne cat - && echo "stream not empty"

ifne only executes, if the stream is non-emty. But how can I make the second command (echo "stream not empty") also execute only if non empty? As it is now, in following case echo is executed (but I don't want it to be executed):

printf "" | ifne cat - && echo "stream not empty"

using parenthesis gives me syntax error:

printf "" | ifne (cat - && echo "stream not empty")

How can I execute the last command only if stream is non-empty?

share|improve this question
up vote 1 down vote accepted

ifne doesn't set an exit code based on whether the input is empty or not, so && and || aren't going to work as hoped. An alternate approach to Babyy's answer is to use pee from the same package:

printf "asdf\n" | pee 'ifne cat -' 'ifne echo "stream not empty"'

This works like tee, but duplicates the input stream into a number of pipes, treating each argument as a command to run. (tpipe is a similar command, but behaves slightly differently.)

A possible issue though is that each of the commands may be writing to stdout in parallel, depending on buffering and length of input/output there is a chance that output will be interleaved, or vary from run to run (effectively a race). This can probably be eliminated using sponge (same package) instead of cat, and/or other buffering/unbuffering solutions. It affects the example you gave, but may not affect your real use-case.

share|improve this answer

use this format :

printf "" | ifne bash -c  "cat - ; echo 'stream not empty' "

output is none, and

printf "bb\n" | ifne bash -c  "cat - ; echo 'stream not empty' "

output is:

stream not empty
share|improve this answer
Note that there's nothing bash-specific in that cat -; echo 'stream not empty' command line. Any sh implementation would interpret it just the same (even csh or rc based shells would interpret it the same), no need to install bash just for that. Even on systems where bash is installed, sh is likely to be leaner than bash so it would still make more sense to use sh than bash there. – Stéphane Chazelas Jun 12 at 21:07

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.