bash将stdout发送到一个过程,然后将stderr发送到另一个过程
我有一个有关过程替代和抗议重定向的问题。
考虑一下
$ zzz > >(echo fine) 2> >(echo error)
我期望输出fine错误
,因为zzz不是有效的命令,而是我得到fine
。为什么这是?
这是按预期工作的
$ zzz 2> >(echo error)
error
如果我交换订单,
$ zzz 2> >(echo error) >(echo fine)
fine
error
I have a question on process substitution and bash redirection.
Consider
$ zzz > >(echo fine) 2> >(echo error)
I expected output fine error
since zzz is not a valid command but instead I just get fine
. Why is this?
This works as expected
$ zzz 2> >(echo error)
error
If I swap the order
$ zzz 2> >(echo error) >(echo fine)
fine
error
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是因为BASH将输出重定向应用于
echo Error
进程以及zzz >>>(echo fine)
part) >命令本身。由于echo fine
对该输入没有任何作用,因此“错误”文本仅消失。您可以通过将Echo Fine
替换为输入的内容来看到这一点:请注意(至少在我尝试过时),这看起来很奇怪,因为外壳打印了下一个提示(“ $ ”)
sed
在输出修改后的错误消息之前。由>()创建的子过程有效地背景,因此Shell不会等待它们完成。
如果要避免使用此功能(或至少绕过它),则可以将Stdout文件描述符复制到其他FD,然后将输出从另一个过程重定向到该替代FD。这是一个使用fd#3:
btw的 示例
Echo Fine
的输出按照终端的形式为正常。另一方面,如果这样做,则会从echo fine
命令中发生错误,将被重定向到echo Error
。(在此示例中,
xxx
和yyy
均已发送到echo错误
, yyy 都忽略了它们。) ^2,ZSH还实现了过程替代,但并未采用这种方式使用继承的重定向:
据我所知,流程替代不是任何标准定义的,所以我认为没有一种方法可以定义哪种外壳的实现是“更正确”。
It's because bash applies the output redirection (the
> >(echo fine)
part) to theecho error
process as well as to thezzz
command itself. Sinceecho fine
doesn't do anything with that input, the "error" text just vanishes. You can see this by replacingecho fine
with something that actually displays what it got as input:Note that (at least when I tried it), this looks weird because the shell printed its next prompt ("$ ") before
sed
got around to outputting the modified error message. The subprocesses created by>( )
are effectively backgrounded, so the shell doesn't wait for them to finish.If you want to avoid this (or at least work around it), you can copy the stdout file descriptor to a different FD, then redirect output from the other process to that alternate FD. Here's an example using FD #3:
BTW, if you put the redirects in the other order, the redirect to
echo fine
happens logically after theecho error
process is started, soecho fine
's output goes to the terminal as normal. On the other hand, if you do it that way, then errors from theecho fine
command would be redirected toecho error
.(In this example, the "command not found" errors for both
xxx
andyyy
are sent toecho error
, which ignores them.)BTW^2, zsh also implements process substitution, but doesn't apply inherited redirects this way:
As far as I know, process substitution isn't defined by any standard, so I don't think there's a way to define which shell's implementation is "more correct".