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:
They use the ls -al and ls -Al commands - both of which output non-empty strings in empty directories.
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.
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.
The no-op command in shell is : (colon). Do nothing beyond expanding arguments and performing redirections. The return status is zero.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With