【问题标题】:Why does command-with-error | grep 'regex-not-matching-error' still print an error?为什么命令错误| grep 'regex-not-matching-error' 仍然打印错误?
【发布时间】:2021-05-12 08:59:00
【问题描述】:

我正在学习 bash。 我运行了以下代码并得到了一些输出,

$ cat non_exist_file | grep -e 'dummy'
  cat: non_exist_file: No such file or directory

这对我来说很奇怪,因为我预计输出应该什么都没有。

我已经阅读了下面 bash 手册中的说明,

Pipelines

[time [-p]] [ ! ] command [ [|⎪|&] command2 ... ]
...
If |& is used, command's standard error, in addition to its standard output,
is connected  to  command2's  standard input through the pipe; it is shorthand
for 2>&1 |.

根据上面的指令,我预计管道会传递错误消息,

cat: non_exist_file: No such file or directory

到 grep 作为标准输入。最终输出将是空的,因为错误消息中的任何单词都不匹配。但是我收到了错误消息。

上面的代码发生了什么?恐怕我做了一个廉价的误会。请教我。

【问题讨论】:

    标签: bash


    【解决方案1】:

    另一个与上一个答案结果相同的选项,这会将 stderr 重定向到 stdout

    cat non_exist_file 2>&1 | grep -e 'dummy'
    

    【讨论】:

      【解决方案2】:

      | 仅连接标准输出,但cat 将错误消息(如预期)打印到标准错误

      正如手册页所说,使用|& 也将标准错误 连接到grep标准输入

      cat non_exist_file |& grep -e 'dummy'
      

      【讨论】:

      • 我不知道 |& 是一个单词。我虽然这意味着|和 &。谢谢。
      • @mora,如果它们分别具有它们的原始含义,|& 将没有意义 - & 将前面的命令放在后台,但如果后面的命令它在管道中位于前台,& 可能没有合理的含义,因为以下前台命令仍然需要等到它可以读取其标准输入。
      • @Charles Duffy:感谢您的友好评论。我误解了“|& is used”是“| or &”被使用了。而且我没有注意 & 部分是什么意思,因为我专注于 '|'。但无论如何,这仍然是我奇怪的误会……再次感谢您。
      猜你喜欢
      • 2011-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-21
      • 2021-10-09
      • 2011-11-05
      相关资源
      最近更新 更多