Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test whether a command output is non-empty in POSIX shell?

How to efficiently check whether an arbitrary command produced any output in POSIX shell? (Let's say git ls-files --killed.)

There are three obvious ways, but each seems ugly or evil to me:

  1. [ -n "$(git ls-files --killed)" ] - the complete output of the command has to be captured in memory and passed to test (which is at least hopefully a builtin)
  2. [ "$(git ls-files --killed | wc -c)" -gt 0 ] - two fork-execs involved
  3. TMP=$(tempfile); git ls-files --killed >"$tempfile"; [ -s "$tempfile" ] && ...; rm "$tempfile" - an intermediate temporary file (again capturing all the output, too) is required
like image 520
Petr Baudis Avatar asked Jun 28 '13 00:06

Petr Baudis


People also ask

How do you check if output of a command is empty or not?

They use the ls -al and ls -Al commands - both of which output non-empty strings in empty directories.

How do you check whether a file is empty or not in shell script?

Bash Script – Check If File is Empty or Not With the -s Option. However, one can pass the -s option as follows in script or shell prompt: touch /tmp/f1 echo "data" >/tmp/f2 ls -l /tmp/f{1,2} [ -s /tmp/f1 ] echo $? The non zero output indicate that file is empty.

How do I check if a string is empty in bash?

To check if string is empty in Bash, we can make an equality check with the given string and empty string using string equal-to = operator, or use -z string operator to check if the size of given string operand is zero.

What is the do nothing shell command?

The no-op command in shell is : (colon). Do nothing beyond expanding arguments and performing redirections. The return status is zero.


2 Answers

You can check the exit status of the command also. Usually, commands if successfuly run, return an exit status of 0.

git ls-files --killed > /dev/null
if [ $? -eq 0 ]

OR if you want to only depend on the output of the command , you can use the "head -1" along with you 1st option since anyway it looks you are not doing any processing with your command output apart from knowing the result.

like image 90
Guru Avatar answered Sep 28 '22 09:09

Guru


My preferred solution uses POSIX shell builtin read

if git ls-files --killed | read REPLY; then
  echo "Some output"
else
  echo "No output or git failed"
fi

read attempts to read a line from stdin (and into the variable REPLY), and returns 0 if successful, or a positive exit code if failed. The rest of the pipeline is not read. In bash only, REPLY is the default name if omitted, so read REPLY may be shortened to just read.

A potential downside of this approach is that the exit code of the program in question (git in your example) is not checked.

like image 27
kkm Avatar answered Sep 28 '22 09:09

kkm