【问题标题】:How to check if pipe content (stdout) is empty in bash [duplicate]如何检查bash中的管道内容(stdout)是否为空[重复]
【发布时间】:2019-02-21 14:16:17
【问题描述】:

一些例子:

我有一个 shellscript,我想检查命令的标准输出是否为空。 所以我可以做

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

但是没有直接的命令来检查这个吗?类似的东西:

if whateverbin | checkifstdinisempty ; then
  echo no content
fi

【问题讨论】:

    标签: bash


    【解决方案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
    

    【讨论】:

    • -z 可以是omitted
    • 这不起作用的命令输出只包含 ASCII NUL 字符和换行符。试试[[ -z $(printf '\n\0\n') ]] && echo EMPTY。问题中的代码正确地将printf 输出标识为非空。
    【解决方案2】:

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

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

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

    【讨论】:

      【解决方案3】:
      [[ `echo` ]] && echo output found || echo no output
      

      --> 没有输出

      [[ `echo something` ]] && echo output found || echo no output
      

      --> 找到输出

      如果:

      if [ `echo` ] ; then echo ouput found; else echo no output; fi
      

      【讨论】:

      • Plain echo 确实会产生输出(单个换行符),并且问题中的代码可以识别这一点。此方法无法处理仅包含 ASCII NUL 字符和换行符的输出。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-26
      • 1970-01-01
      • 2012-11-28
      相关资源
      最近更新 更多