$ echo Hello world > file
$ echo Hello > file world
$ echo > file Hello world
$ > file echo Hello world
他们都做同样的事情,但我不知道为什么。
来自 man bash
:
Simple Commands
A simple command is a sequence of optional variable assignments fol-
lowed by blank-separated words and redirections, and terminated by a
control operator. The first word specifies the command to be executed,
and is passed as argument zero. The remaining words are passed as
arguments to the invoked command.
也就是说,它没有指定“单词和重定向”的顺序。 在REDIRECTIONS部分中:
REDIRECTION
[...]
The [...] redirection opera-
tors may precede or appear anywhere within a simple command or may fol-
low a command. Redirections are processed in the order they appear,
from left to right.
[...]
所以它们可以出现在任何地方。
正如你自己也观察到的那样,它们在结果上没有区别。但可读性确实有所不同。
这是最直观的写法:
echo Hello world > file
非常易于理解。 >
看起来像一个箭头,是吧。
其他的不太直观,不够可读。 我建议坚持第一种书写风格。
>
)在命令行上技术上可以出现在任何位置。虽然第一个选项是“传统”的,但其他选项都会执行相同的操作,因为它们会将输出重定向到文件(> 文件名
),然后再执行命令行中剩余的内容。 - Marc B