【问题标题】:check if the output of "cat" is not empty检查“cat”的输出是否不为空
【发布时间】:2013-07-29 10:35:04
【问题描述】:

是否可以知道以下命令的输出是否为空?

cat anyfile.txt | grep anymessage

没有将显示的输出放入变量中,也没有将显示的输出重定向到文件

【问题讨论】:

    标签: linux bash shell sh


    【解决方案1】:

    如果未找到匹配项,则 grep 命令以状态 1 退出。您可以像这样使用退出状态:

    whatever | grep pattern
    echo $?
    

    您甚至可以在 shell 脚本中编写:

    if whatever | grep pattern ; then
         # match was found
    else
         # not found
    fi
    

    【讨论】:

      【解决方案2】:

      如果您执行grep 'sometext' anyfile.txt >/dev/null,则不会打印任何内容。

      但是,如果您在之后阅读$?,则如果匹配行将显示 0,否则将显示 1。

      【讨论】:

        【解决方案3】:

        你可以告诉 grep -q 保持安静:

        if  grep -q anymessage anyfile.txt ; then
            # found
        else
            # not found
        fi
        

        【讨论】:

          【解决方案4】:

          您可以编写一个带有 if 语句的小脚本并打印出 true 或 false。

          【讨论】:

            【解决方案5】:

            也可以使用“grep -c anymessage anyfile.txt”(-c 获取匹配数)

            【讨论】:

              猜你喜欢
              • 2018-05-26
              • 1970-01-01
              • 2017-06-14
              • 2018-09-30
              • 2015-01-11
              • 2013-03-05
              • 2018-04-18
              • 1970-01-01
              相关资源
              最近更新 更多