&> >& 和 2>&1 之间的重定向区别

Ame*_*ina 14 shell zsh io-redirection

这个 SO 线程和其他一些线程上,我看到了以下用于重定向stdoutstderr到文件的命令。

它们都是等价的吗?它们之间有什么区别吗?

command1 >> logfile 2>&1
command &> logfile
command >& logfile
Run Code Online (Sandbox Code Playgroud)

Cit*_*ght 8

由于您已标记zsh,让我告诉您所有 3 种重定向的工作方式完全相同。正如您可能在两个重复的帖子(评论中的一个和您的帖子中的一个)中读到的那样,它们都重定向stderrstdout哪个 inturn 被重定向到文件“日志文件”(即,日志文件将包含输出和错误)。

但是它们的行为会根据您所在的 shell 发生很大变化。

所有三种风格重定向的效果很好,在以同样的方式bashzsh

但:

>&适用于cshtcsh

[soum@server ~]$  ./test.sh > logfile 2>&1
Ambiguous output redirect.
[soum@server ~]$ ./test.sh &> logfile
Invalid null command.
[soum@server ~]$ ./test.sh >& logfile
[soum@server ~]$ echo $SHELL
/bin/tcsh
[soum@server ~]$
Run Code Online (Sandbox Code Playgroud)

ksh唯一的2>&1作品。

$ ./test.sh >& logfile
-ksh: logfile: bad file unit number
$ ./test.sh &> logfile
[1]     23039
$ 1  2  3  4  5  6  logfile  test.sh
ls: cannot access ttr: No such file or directory

[1] +  Done(2)                 ./test.sh &> logfile
Run Code Online (Sandbox Code Playgroud)

我讨厌ksh。虽然>&只是给出了一个错误,但&>后台命令的一部分并清空了日志文件(如果非空)。