目前我正在编写一个小 shell(重定向、管道、exec 等)。一直试图找出 Linux shell 在处理 I/O 重定向时所采取的步骤。
关于我需要帮助的一些问题:
无论如何,我能想到的一些是(如果我错了,请纠正我):
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
现在我不知道以下情况的过程(如 shell 如何查找和处理这些)。
我不知道 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 ^
最佳答案
只要您只重定向 stdin 和 stdout,处理重定向的顺序就无关紧要,因此最后两个示例完全相同。
BASH 从左到右处理 IO 重定向。
> cmd1 > file 2>&1
> cmd2 2>&1 > file
这两个是不同的。在第一种情况下,我将 stdout 绑定(bind)到
file
,然后将 stderr 绑定(bind)到 stdout:现在 stderr 和 stdout 都进入文件。在第二种情况下,我将( child 的)stderr 绑定(bind)到( parent 的)stdout,然后我找到 child 的 stdout 要归档。结果是您现在在 stdout 上获得 child 的 stderr 输出,并且 stdout 进入文件。例如,这对于在管道中处理 stderr 很有用。
如果查看 BASH 的源代码,可以看到一个命令的执行分为几个步骤:
关于linux - Linux shell 中的 I/O 流重定向。 shell 如何处理带有重定向的命令?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20215401/