将 stderr 和 stdout 重定向到 Bash 中的文件的不同方法?

Different ways to redirect stderr and stdout to a file in Bash?

据我了解,2>&1就是'send stderr to the same place as stdout'。但出于某种原因,1>foo 2>foo1>foo 2>&1 似乎并不等同。

# Assuming file 'out' exists but file 'nosuchfile' doesn't

# 'foo' contains stdout and some partial stderr in CentOS 6
$ ls -l out nosuchfile 1>foo 2>foo
$ cat foo
-rw-r--r-- 1 user user 0 May 14 14:45 out
ctory

# 'foo' contains both stdout and stderr
$ ls -l out nosuchfile 1>foo 2>&1
$ cat foo
ls: cannot access nosuchfile: No such file or directory
-rw-r--r-- 1 user user 0 May 14 14:45 out

谁能解释为什么他们的行为不同?

> 覆盖文件; >> 附加到文件。

当你编写 1> file 2> file 时,两个流将并行覆盖 file,因此可能会相互覆盖 - 典型的比赛条件。

command 1>> file 2>> file 应保留两个流的所有输出。

示例:

$ n=1""000""000
$ (seq "$n" 1>&2 & seq "$n") 1> o 2> o
$ wc -l o
1000000
$ rm o
$ (seq "$n" 1>&2 & seq "$n") 1>> o 2>> o
wc -l o
2000000