Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

How can I test whether a command's output is an empty string without interfering with said output? Example:

command | ???
if [ $? = 0 ] && [ -n "$output_from_command"]; then
   ...

I'd like that the output from the code above be the same as when running command.

share|improve this question

3 Answers 3

up vote 4 down vote accepted

You can use the tee command, which accepts input from stdin and writes the output to stdout plus a file.

command | tee /tmp/out.$$

Then you can test /tmp/out.$$ to see whether it is of zero length or not. (Note that $$ expands to the current pid, which helps avoid similar processes overwriting one another.)

share|improve this answer
    
I think I can tee to /dev/tty and avoid the temp file: out=$(echo 'hi'|tee /dev/tty) –  Ernest A Dec 23 '13 at 21:15

This seems to work:

#!/bin/bash

OUTPUT="$(echo "foo")"  # replace 'echo "foo"' with your command

if [[ -z "$OUTPUT" ]]; then
   echo "No output."
else
   echo "$OUTPUT"
fi
share|improve this answer
1  
Yes, it works, but has the disadvantage that lines are printed all at once, whereas command may print lines at a certain rate. –  Ernest A Dec 23 '13 at 21:17
    
Yeah, if you want to see the output in real time, tee is probably your best bet. –  DopeGhoti Dec 23 '13 at 21:25
1  
That assumes no NUL character in the output, that the output is not -n or -nene... and it will remove the trailing newlines characters (and add one back). –  Stéphane Chazelas Dec 23 '13 at 22:15
if the-command | grep '^'; then
  echo the-command output was not empty
fi

(note that the behaviour will vary across grep implementations if the output of the-command is not text (contains NUL characters, doesn't end in a newline character or has abnormally long lines).

share|improve this answer

Your Answer

 
discard

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.