&> 测试或 > 测试 2>&1

Abs*_*cDo 4 bash

我从&>用于处理错误和数据的指令中读取

$ls -al test test2 test3 badtest &> test7
$ cat test7
ls: cannot access 'test': No such file or directory
ls: cannot access 'badtest': No such file or directory
-rw-r--r-- 1 me staff 78 Oct 28 19:07 test2
-rw-r--r-- 1 me staff  0 Oct 28 19:03 test3
Run Code Online (Sandbox Code Playgroud)

尽管如此,当我检查过时和不推荐使用的语法 [Bash Hackers Wiki]

它推荐 2>&1

$ ls -al test test2 test3 badtest > test7 2>&1

 $ cat test7
ls: cannot access 'test': No such file or directory
ls: cannot access 'badtest': No such file or directory
-rw-r--r-- 1 me staff 78 Oct 28 19:07 test2
-rw-r--r-- 1 me staff  0 Oct 28 19:03 test3
Run Code Online (Sandbox Code Playgroud)

我应该遵循哪种模式

Kus*_*nda 8

这由您来决定。

bash外壳的理解&>file,并>file 2>&1为相同的,你可以使用以前的语法编写后者的快捷方式。其他 shell 可能会抛出语法错误或使用&>.

如果您编写bash脚本(而不是用于 eg 的脚本/bin/sh),那么一定要使用&>,但如果您发现自己想要或需要编写可移植脚本(需要在其下运行/bin/sh或应该由任何sh类似 shell执行的脚本,这bash是一个和kshzsh并且dash是其他),然后&>是您应该避免的事情之一。

所有的sh样弹实现POSIX标准的句法和语法方面,而是bash和另一个外壳还提供了语法便利设施,如&>和扩展如数组和正则表达式匹配等,还有一些炮弹可能相当不同方式,对POSIX标准的扩展bash是正在做。

有关的:

  • 除了这个特殊的“功能”不仅仅是一个扩展,因为它与 POSIX 不兼容,正如在 OP 问题的链接中清楚地解释的那样:“它们还引入了解析歧义,并且**与 POSIX 冲突**。没有此功能将 cmd1 &>file cmd2 视为:“后台 cmd1 然后执行 cmd2 并将其 stdout 重定向到文件”,**这是该表达式的正确解释**”。事实上,其他 shell 会默默地将它解释为其他东西 * 根据标准 * 很明显,永远不应该使用这种语法。 (5认同)