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

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

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

最佳答案

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

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

cat non_exist_file |& grep -e 'dummy'

关于bash - 为什么命令错误| grep 'regex-not-matching-error' 仍然打印错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66106967/

相关文章:

regex - 这个 BASH 正则表达式有什么问题

bash - 第一次使用 getopts 运行脚本有效,但第二次运行它时不起作用

bash - 使用 ssh key 以用户身份 rsync 文件

linux - 环境变量中的波浪号扩展

bash - 嵌套的 Herodoc 操作顺序

linux - 动态评估字符串中的变量值

bash - 我可以从命令行批量删除 pdf 中的链接吗?

bash - Bash 中的动态变量名称

java - 单次登录 SSH,共享 session 来运行 git-receive-pack 并远程运行一些其他命令

linux - 用于查找文件中每个字母出现频率的 Bash 脚本