为什么重定向+管道(2>&1 |)会合并两个流而不是将stderr移动到stdout?

4
我了解到重定向是从左到右处理的。因此,在这个例子中:
 command 2>&1 | less

有人会认为fd 2首先被定向到fd 1,然后fd 1被发送到管道。所以fd 1和2指向不同的位置。

但实际上,在这里,fd 1和2都指向管道,因为由于某种原因,fd 1首先被发送到管道,然后fd 2被发送到fd 1。为什么在这种情况下重定向从右向左处理?

3个回答

3

文件描述符2被定向到文件描述符1指向的位置(也就是标准输出)。在

command 2>&1 | less

在重定向生效之前,stdout已经指向管道!

更详细的解释请参见:

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

3
管道不是重定向,因此实际上重定向(在您的示例中只有一个)正在按照您的想法进行处理。管道是另一件事情,在结尾处。

3

原因是管道和重定向不同。重定向只影响一个命令,而管道连接了两个命令。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接