如何在bash [duplicate]中检查管道内容(stdout)是否为空

问题描述 投票:1回答:3

这个问题在这里已有答案:

一些例子:

我有一个shell脚本,我想检查一个命令的stdout是否为空。所以我能做到

if [[ $( whateverbin | wc -c) == 0 ]] ; then
  echo no content
fi

但是没有直接命令来检查这个吗?就像是 :

if whateverbin | checkifstdinisempty ; then
  echo no content
fi
bash
3个回答
1
投票

您可以使用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

1
投票

试着只读一个字;没有输入,read将失败。

if ! whateverbin | IFS= read -n 1; then
    echo "No output"
fi

如果read失败,则整个管道失败,并且!否定非零退出状态,以便整个条件成功。


0
投票
[[ `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
© www.soinside.com 2019 - 2024. All rights reserved.