问题
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