7

Is there a simple utility which I can pipe output to on Linux that will:

  • Return a success code if there is no output on standard out (and / or standard error).
  • Return a failure code if output is produced on standard out (and / or standard error).

To provide some context, the command I'm running is:

svn mergeinfo --show-revs eligible
http://mysvnserver.example.com/SVF/repos/common/abc/branches/abc-1.7
http://mysvnserver.example.com/SVF/repos/common/abc/trunk

If there are any unmerged entries on the branch, the command will return a list of revision numbers on standard out. Ideally, the additional command that I'm talking about would:

  • Detect entries on standard out and return an error condition to Linux.
  • Pass on the standard out so that it does end up appearing on the terminal. I'd rather not suppress it.
David B
  • 203
  • 3
  • 6

3 Answers3

11

That's grep you're looking for:

if svn ... 2>&1 | grep '^'; then
  echo "there was some output"
else
  echo "there wasn't"
fi

You can replace grep '^' with grep . or grep '[^[:blank:]]' to check for non-empty or non-blank lines (but that will remove the empty/blank ones from the output).

(note the behaviour will vary across grep implementations if the input contains non-text data like NUL bytes or too long or non-terminated lines (which wouldn't happen for svn though)).

1

I don't know of one existing command... is roll-your-own not acceptable? A wrapper? tee the output to a file and exit based on whether the file is empty of not?

Wrapper approach, assuming you still want to see the output and keep stdout and stderr separate in the output.

#!/bin/bash

TMPFILE=/tmp/allout.$$
TMPPIPE=/tmp/errout.$$
SAVERC=/tmp/saverc.$$

cleanup() {
   [ -p $TMPPIPE ] && rm $TMPPIPE
   [ -f $TMPFILE ] && rm $TMPFILE
}
trap cleanup EXIT

# Set up output/display of std err
[ -p $TMPPIPE ] || mkfifo $TMPPIPE
cat $TMPPIPE | tee -a $TMPFILE1 >&2 &

(eval "$*" 2>$TMPPIPE
echo $? > $SAVERC
) | tee -a $TMPFILE

[ -s $TMPFILE ] && exit 1
exit $(cat $SAVERC)
Johan
  • 4,148
0

You can use wc to count the characters in the output.

$ [ $(ls 2>&1 | wc -c) = "0" ]
$ echo $?
1
$ [ $(echo -n '' 2>&1 | wc -c) = "0" ]
$ echo $?
0

The 2>&1 is required to redirect the stderr to stdout.

Martin Tournoij
  • 1,715
  • 2
  • 15
  • 35