Why does command-with-error | grep 'regex-not-matching-error' still print an error?

妖精的绣舞 提交于 2021-02-17 05:13:47

问题


I am learning bash. I ran following code and got some output,

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

It was strange for me because I expected the output should have nothing.

I have read a instruction in bash manual below,

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 |.

On the basis instruction above, I expected the pipeline passes the error message,

cat: non_exist_file: No such file or directory

to the grep as standard input. And the final output will be nothing because any word in the error message does not match. However I got the error message.

What is happened to the code above? I am afraid I made a cheap misunderstanding. Please teach me.


回答1:


| only connects standard output, but cat prints the error message (as expected) to standard error.

As the man page says, use |& to also connect standard error to grep's standard input:

cat non_exist_file |& grep -e 'dummy'



回答2:


another option with same result as the last answer, this will redirect stderr to stdout

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


来源:https://stackoverflow.com/questions/39619849/why-does-command-with-error-grep-regex-not-matching-error-still-print-an-err

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!