据我了解,2>&1
只是表示“将 stderr 发送到与 stdout 相同的位置”。但出于某种原因,1>foo 2>foo
和 1>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
关于linux - 将 stderr 和 stdout 重定向到 Bash 中的文件的不同方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56140195/