我了解到重定向是从左到右处理的。因此,在这个例子中:
command 2>&1 | less
有人会认为fd 2首先被定向到fd 1,然后fd 1被发送到管道。所以fd 1和2指向不同的位置。
但实际上,在这里,fd 1和2都指向管道,因为由于某种原因,fd 1首先被发送到管道,然后fd 2被发送到fd 1。为什么在这种情况下重定向从右向左处理?
command 2>&1 | less
有人会认为fd 2首先被定向到fd 1,然后fd 1被发送到管道。所以fd 1和2指向不同的位置。
但实际上,在这里,fd 1和2都指向管道,因为由于某种原因,fd 1首先被发送到管道,然后fd 2被发送到fd 1。为什么在这种情况下重定向从右向左处理?
文件描述符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.
# ...
原因是管道和重定向不同。重定向只影响一个命令,而管道连接了两个命令。