为什么命令错误| grep' regex-not-matching-error'仍然打印错误?

时间:2016-09-21 14:47:21

标签: bash

我正在学习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作为标准输入。并且最终输出将无效,因为错误消息中的任何单词都不匹配。但是我收到了错误消息。

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

2 个答案:

答案 0 :(得分:2)

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

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

cat non_exist_file |& grep -e 'dummy'

答案 1 :(得分:2)

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

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