在 Mark Sobell 的 Linux 命令、编辑器和 Shell 编程实用指南,第二版中,他写道(第 432 页):
The <& token duplicates an input file descriptor; >& duplicates an output file descriptor.
这似乎与同一页上的另一个说法不一致:
Use the following format to open or redirect file descriptor n as a duplicate of file descriptor m:
exec n<&m
在同一页上还有一个例子:
# File descriptor 3 duplicates standard input
# File descriptor 4 duplicates standard output
exec 3<&0 4<&1
如果 >& 复制一个输出文件描述符那么我们不应该说
exec 4>&1
复制标准输出?
最佳答案
这个例子在实践中是正确的。这本书的原始解释是对 POSIX 标准所说内容的准确描述,但我手边的类 POSIX shell( bash
和 dash
,我认为唯一在 Linux 上常见的)并不那么挑剔。
POSIX 标准 says the same thing as the book关于输入和输出描述符,然后继续说:for n<&word
, “如果 word
中的数字不代表已经打开供输入的文件描述符,则会导致重定向错误”。因此,如果您想注意 POSIX 兼容性,则应避免这种用法。
bash 文档也 says the same thing关于<&
和 >&
,但没有错误的 promise 。这很好,因为它实际上并没有给出错误。相反,凭经验 n<&m
和 n>&m
似乎可以互换。 <&
之间的唯一区别和 >&
就是如果你去掉左边的 fd 编号,<&
默认为 0(标准输入)和 >&
到 1(标准输出)。
例如,让我们启动一个 shell,fd 1 指向一个文件 bar
,然后准确地尝试 exec 4<&1
例如,尝试写入生成的 fd 4,看看它是否有效:
$ sh -c 'exec 4<&1; echo foo >&4' >bar; cat bar
foo
确实如此,并且使用 dash
都成立。或 bash
(或 bash --posix
)用于 shell 。
在幕后,这是有道理的,因为 <& 和 >& 几乎肯定只是在调用 dup2() ,它不关心 fds 是否打开用于读取、写入或追加等等。
[编辑:在评论中讨论后添加了对 POSIX 的引用。]
关于linux - exec n<&m 与 exec n>&m —— 基于 Sobell 的 Linux 书,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5878384/