【问题标题】:Different ways to redirect stderr and stdout to a file in Bash?将stderr和stdout重定向到Bash中的文件的不同方法?
【发布时间】:2019-05-15 00:14:04
【问题描述】:

据我了解,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

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

【问题讨论】:

标签: linux bash stdout stderr


【解决方案1】:

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

当您编写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

【讨论】:

    猜你喜欢
    • 2014-07-22
    • 1970-01-01
    • 1970-01-01
    • 2010-10-14
    • 2016-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    相关资源
    最近更新 更多