stdin 重定向的 posix 位置(<in cmd vs cmd <in)

Car*_*rós 8 shell io-redirection posix

我总是在命令之后写 stdin 重定向,因为对我来说,首先命令然后重定向(如果有)更自然:

some-command < input-file > output-file
Run Code Online (Sandbox Code Playgroud)

多年来,我看到人们在命令之前编写 stdin 重定向,以获得一些流程方向:

< input-file some-command > output-file (or without spaces after < and > )
Run Code Online (Sandbox Code Playgroud)

这个顺序是被 POSIX 接受还是被许多 shell 接受(在我的 Fedora 21 中,它被bash, dash, tcsh,ksh和接受zsh)?

cuo*_*glm 8

这种行为是由 POSIX在这里定义的:

如果一个命令指定了多个重定向运算符,则计算顺序为从开始到结束。

这里

“简单命令”是一系列可选的变量赋值和重定向,以任何顺序,可选地跟随单词和重定向,由控制运算符终止。

Bourne shell 中已经是这种情况,POSIX 以此为基础。

在执行命令之前,它的输入和输出可以使用由 shell 解释的特殊符号重定向。以下可能出现在简单命令中的任何位置,也可能出现在命令之前或之后,并且不会传递给调用的命令。(…)

与原来的Bourne shell,POSIX不允许重定向到前面一个复杂的命令一样while … done( … )等等。


请注意重定向的顺序很重要,因为它控制您的命令行为并防止您在失败时出现一些奇怪的结果。例子:

command <input >output
Run Code Online (Sandbox Code Playgroud)

如果command读取失败input(由于权限,不存在......)那么output如果交换重定向位置,它将被终止而不创建空文件:

command >output <input
Run Code Online (Sandbox Code Playgroud)