I/O stream redirection in a Linux shell. How does the shell process a command with redirection?

两盒软妹~` 提交于 2019-12-01 19:03:58

As long as you only redirect stdin and stdout, the order in which the redirections are processed don't matter so the last two examples are exactly the same.

BASH processes IO redirection from left to right.

> cmd1 > file 2>&1
> cmd2 2>&1 > file

These two are different. In the first case, I bind stdout to file and then bind stderr to stdout: Both stderr and stdout now go into the file.

In the second case, I bind (the child's) stderr to stdout (of the parent) and then I find the child's stdout to file. The result is that you now get the child's stderr output on stdout and the stdout goes to the file. This is useful for processing stderr in a pipe, for example.

If you look at the source code of BASH, you can see that the execution of a command is split in several steps:

  • Replace all variables
  • Split input into "words"
  • Process IO redirection (and remove the involved words)
  • Create a new child process with the correct IO setup and the remaining words as arguments.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!