Shell命令以">"开头

Rya*_*yan 7 bash shell

我最近遇到了一个看起来像这样的shell命令:"> outfile <infile cat",它似乎在功能上等同于"cat infile> outfile".就此而言,一般形式似乎是"> outfile <infile命令arg1 ... argN"变为"命令arg1 ... argN infile> outfile".

无论如何,我想知道是否有人可以详细说明领先的">"如何实现这种效果,以及是否有任何实际用途.

Mic*_*urr 6

"Bash的参考手册"说,关于重定向操作符如下:

以下重定向运算符可以在简单命令之前或出现在任何位置,也可以跟随命令.

所以以下命令都是等效的:

ls -al > listing.txt
> listing.txt ls -al
ls > listing.txt -al
Run Code Online (Sandbox Code Playgroud)

虽然我猜第一种是最常见的形式.

请注意,重定向的相对顺序很重要,因此,例如,如果要将一个文件描述符重定向到另一个文件描述符,则以下内容会有所不同:

ls > listing.txt 2>&1   # both stdout and stderr go in to listing.txt

ls 2>&1 > listing.txt   # only stdout goes to listing.txt, because stderr was made
                        #    a copy of stdout before the redirection of stdout
Run Code Online (Sandbox Code Playgroud)