简体   繁体   English

Linux shell中的I / O流重定向。 shell如何使用重定向处理命令?

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

Currently I'm coding a small shell (redirection, pipes, exec, etc.). 目前我正在编写一个小shell(重定向,管道,exec等)。 Been trying to figure out the steps the Linux shell takes in addressing I/O redirection. 一直试图弄清楚Linux shell在解决I / O重定向方面所采取的步骤。

Some questions on what I need help on: 关于我需要帮助的一些问题:

  1. In which direction does the shell read from the command line when it is looking for the redirection? shell在寻找重定向时从命令行读取的方向是什么? Left to right or the opposite? 从左到右还是相反? Uses recursion? 使用递归?

  2. What are the cases the shell needs to look for? shell需要寻找什么情况? (not sure if there are many or just a couple that can encompass a lot of variation) (不确定是否有很多或只有一对可以包含很多变化)

Anyways, some I can think of are (correct me if I'm wrong): 无论如何,我能想到的是(如果我错了,请纠正我):

cmd > file1       # stdout of cmd goes to file

cmd file1 > file2 # stdout of cmd with file1 as an argument goes to file2

cmd file2 < file1 # stdin on file2 comes from file1

Now I don't know the process on the following cases (as in how the shell looks for and handles these). 现在我不知道以下情况的过程(如shell查找和处理这些情况)。 The steps the shell takes are unbeknown to me shell采取的步骤对我来说并不为人所知

cmd file2 > file3  < file1 # using "tee" in place of "cmd" I don't know
                           # how to do the dups and when to exec

cmd file2 < file3 > file1  # same ^

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. 只要您只重定向stdin和stdout,处理重定向的顺序无关紧要,因此最后两个示例完全相同。

BASH processes IO redirection from left to right. BASH从左到右处理IO重定向。

> 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. 在第一种情况下,我将stdout绑定到file ,然后将stderr绑定到stdout:stderr和stdout现在都进入文件。

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. 在第二种情况下,我将(孩子的)stderr绑定到stdout(父节点),然后我找到孩子的stdout来存档。 The result is that you now get the child's stderr output on stdout and the stdout goes to the file. 结果是你现在在stdout上得到了孩子的stderr输出,stdout转到了文件。 This is useful for processing stderr in a pipe, for example. 例如,这对于处理管道中的stderr非常有用。

If you look at the source code of BASH, you can see that the execution of a command is split in several steps: 如果查看BASH的源代码,可以看到命令的执行分为几个步骤:

  • Replace all variables 替换所有变量
  • Split input into "words" 将输入拆分为“单词”
  • Process IO redirection (and remove the involved words) 进程IO重定向(并删除涉及的单词)
  • Create a new child process with the correct IO setup and the remaining words as arguments. 使用正确的IO设置创建新的子进程,并将剩余的单词作为参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM