这个问题在这里已有答案:
一些例子:
我有一个shell脚本,我想检查一个命令的stdout是否为空。所以我能做到
if [[ $( whateverbin | wc -c) == 0 ]] ; then
echo no content
fi
但是没有直接命令来检查这个吗?就像是 :
if whateverbin | checkifstdinisempty ; then
echo no content
fi
您可以使用the -z
conditional expression来测试字符串是否为空:
if [[ -z $(ls) ]]; then echo "ls returned nothing"; fi
当您在空结果上运行它时,分支将被执行:
if [[ -z $(cat non-existing-file) ]]; then echo "there was no result"; fi
试着只读一个字;没有输入,read
将失败。
if ! whateverbin | IFS= read -n 1; then
echo "No output"
fi
如果read
失败,则整个管道失败,并且!
否定非零退出状态,以便整个条件成功。
[[ `echo` ]] && echo output found || echo no output
- >没有输出
[[ `echo something` ]] && echo output found || echo no output
- >输出找到了
使用if:
if [ `echo` ] ; then echo ouput found; else echo no output; fi