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

标签 linux bash stdout stderr

据我了解,2>&1 只是表示“将 stderr 发送到与 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

关于linux - 将 stderr 和 stdout 重定向到 Bash 中的文件的不同方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56140195/

相关文章:

linux - 用于 RHEL 的 gdb-multiarch

linux - Jenkins : bash script ran with nohup is neither working nor writing anything to log

bash - 我可以将多个文件输出到 STDOUT 并单独处理它们吗?

python - 如何在 Python 中获取标准输出的硬标签

linux - 在 Linux 中从一个目录移动到另一个目录时使用导出选项

android - Eclipse 和 Android 模拟器 Windows 与 Linux

linux - 如何仅为当前 session 设置 vi 选项?

bash - 加入参数 - 逃生空间

bash 确定变量是否为空,如果是则退出。

java - 如何使用 Java 中默认包中的类?