3

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
0

3 Answers 3

5

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
Sign up to request clarification or add additional context in comments.

2 Comments

the -z could be omitted
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.
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.

Comments

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

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.