2

Some Example:

I've a shellscript where I want to check if a the stdout of a command is empty. So I can do

if [[ $( whateverbin | wc -c) == 0 ]] ; then
  echo no content
fi

But is there no direct command, to check this? Something like :

if whateverbin | checkifstdinisempty ; then
  echo no content
fi
powerpete
  • 2,663
  • 2
  • 23
  • 49

3 Answers3

4

You could use the -z conditional expression to test if a string is empty:

if [[ -z $(ls) ]]; then echo "ls returned nothing"; fi

When you run it on an empty result, the branch gets executed:

if  [[ -z $(cat non-existing-file) ]]; then echo "there was no result"; fi
dulange
  • 281
  • 3
  • 16
  • 1
    the -z could be [omitted](https://stackoverflow.com/questions/12137431/test-if-a-command-outputs-an-empty-string/23532711#23532711) – nullPointer Feb 21 '19 at 14:56
  • This doesn't work of the output of the command consists only of ASCII NUL characters and newline characters. Try `[[ -z $(printf '\n\0\n') ]] && echo EMPTY`. The code in the question correctly identifies the `printf` output as non-empty. – pjh Feb 21 '19 at 19:14
2

Just try to read exactly one character; on no input, read will fail.

if ! whateverbin | IFS= read -n 1; then
    echo "No output"
fi

If read fails, the entire pipeline fails, and the ! negates the non-zero exit status so that the entire condition succeeds.

chepner
  • 497,756
  • 71
  • 530
  • 681
0
[[ `echo` ]] && echo output found || echo no output

--> no output

[[ `echo something` ]] && echo output found || echo no output

--> output found

With if :

if [ `echo` ] ; then echo ouput found; else echo no output; fi
nullPointer
  • 4,419
  • 1
  • 15
  • 27
  • Plain `echo` does produce output (a single newline character), and the code in the question recognizes that. This approach can't handle output that consists only of ASCII NUL characters and newline characters. – pjh Feb 21 '19 at 19:17