2016-09-21 77 views
0

我在学习bash。 我跑到下面的代码,并得到了一些输出,为什么命令与错误| grep'regex-not-matching-error'仍然打印错误?

$ 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

|只连接标准输出,但cat输出错误消息(如预期)到标准误差

由于该男子页说,用|&也连接标准错误grep标准输入

cat non_exist_file |& grep -e 'dummy' 
+0

我不知道|&是一个单词。我虽然意味着|和&。谢谢。 – mora

+1

@mora,如果它们分别具有它们的原始含义,'|'和'&一起就没有意义 - '&'将后面的命令放在后台,但是如果它后面的命令在前景,没有合理的意义,'&'可能有,因为下面的前台命令仍然需要等待,直到它可以读取它的标准输入。 –

+0

@Charles Duffy:谢谢你的评论。我误解了“|&is used”是使用“| or&”。我没有注意到什么和部分的意思,因为我专注于'|'。但无论如何,这仍然是我的奇怪的误解...再次感谢你。 – mora

2

具有相同的结果的另一种选择为最后的答案,这将标准错误重定向到stdout

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