开发者

Why does redirection + pipe ( 2>&1 |) merge both streams instead of moving stderr to stdout?

I read that redirections are processed left to right. So in this example

 command 2>&1 | less

One would think that fd 2 is directed to fd 1 first and t开发者_开发知识库hen fd 1 is sent to pipe. So fd 1 and 2 point to separate places.

But actually here fd 1 and 2 both point to the pipe, because for some reason fd 1 is sent to pipe first and then fd 2 is sent to fd 1. Why are redirections processed right to left in this case?


The pipe is not a redirection, so in fact redirections (of which there is only one in your example) are being processed the way you think. The pipe is a separate thing at the end.


The reason is that pipes aren't the same as redirections. A redirect affects the one command, while a pipe joins two commands.


fd 2 is directed to where fd 1 is pointing to (i.e. stdout). In

command 2>&1 | less

stdout is already pointing to the pipe before the redirections take effect!

For a more detailed explanation see:

http://www.linuxtutorialblog.com/post/tutorial-the-best-tips-tricks-for-bash

# ...
# Well, here's a thing you should remember: bash reads command statements from 
# the left to the right, but, before that, determines if there are multiple command 
# statements and in which way they are separated. Therefore, bash already read 
# and applied the "|" pipe symbol and stdout is already pointing to the pipe.
# ...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜