我从&>
用于处理错误和数据的指令中读取
$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)
我应该遵循哪种模式
这由您来决定。
在bash
外壳的理解&>file
,并>file 2>&1
为相同的,你可以使用以前的语法编写后者的快捷方式。其他 shell 可能会抛出语法错误或使用&>
.
如果您只编写bash
脚本(而不是用于 eg 的脚本/bin/sh
),那么一定要使用&>
,但如果您发现自己想要或需要编写可移植脚本(需要在其下运行/bin/sh
或应该由任何sh
类似 shell执行的脚本,这bash
是一个和ksh
,zsh
并且dash
是其他),然后&>
是您应该避免的事情之一。
所有的sh
样弹实现POSIX标准的句法和语法方面,而是bash
和另一个外壳还提供了语法便利设施,如&>
和扩展如数组和正则表达式匹配等,还有一些炮弹可能相当不同方式,对POSIX标准的扩展bash
是正在做。
有关的:
bash
可移植性的其他问题(DuckDuckGo 搜索链接)。