How to test whether a command output is non-empty in POSIX shell?
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/nullif [ $? -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.
You might think this solution is just as hacky as the others, but I think it uses less memory than the others (I'm no expert in shell script efficiency).
The code is bash only:
z=0while read -r -n1 char; do z=1 breakdone < <(git ls-files --killed)[ $z != 0 ]
It uses a temporary variable instead of a temporary file, and I think read works only one char at a time, but the git ls-files command may still execute fully.
It's may not be much less ugly, but I think it may be at least more efficient.