833

我知道在 Linux 中,要将输出从屏幕重定向到文件,我可以使用>tee. 但是,我不确定为什么部分输出仍然输出到屏幕而不写入文件。

有没有办法将所有输出重定向到文件?

4

9 回答 9

1338

该部分被写入stderr,用于2>重定向它。例如:

foo > stdout.txt 2> stderr.txt

或者如果你想在同一个文件中:

foo > allout.txt 2>&1

注意:这在 (ba)sh 中有效,检查你的 shell 是否有正确的语法

于 2011-07-13T05:10:01.043 回答
162

所有 POSIX 操作系统都有 3 个流:stdin、stdout 和 stderr。stdin 是输入,可以接受 stdout 或 stderr。stdout 是主要输出,使用>>>或重定向|。stderr 是错误输出,它是单独处理的,因此任何异常都不会传递给命令或写入可能破坏的文件;通常,这会被发送到某种日志,或者直接转储,即使在重定向标准输出时也是如此。要将两者重定向到同一个地方,请使用:

$command &> /some/file

编辑:感谢 Zack 指出上述解决方案不可移植——请改用:

$command > file 2>&1 

如果您想消除错误,请执行以下操作:

$command 2> /dev/null
于 2011-07-13T05:16:09.917 回答
110

例如,在控制台和文件file.txt中获取输出。

make 2>&1 | tee file.txt

注意:&(in 2>&1) 指定1不是文件名而是文件描述符。

于 2014-04-09T04:48:59.420 回答
59

用这个 -"require command here" > log_file_name 2>&1

Unix/Linux 中重定向操作符的详细描述。

> 运算符通常将输出重定向到文件,但也可以重定向到设备。您也可以使用 >> 来追加。

如果您未指定数字,则假定为标准输出流,但您也可以重定向错误

> file redirects stdout to file
1> file redirects stdout to file
2> file redirects stderr to file
&> file redirects stdout and stderr to file

/dev/null 是 null 设备,它接受您想要的任何输入并将其丢弃。它可以用来抑制任何输出。

于 2015-06-11T15:57:51.093 回答
46

归功于 osexp2003 和 ja ...</p>


而不是放:

&>> your_file.log

在一行后面:

crontab -e

我用:

#!/bin/bash
exec &>> your_file.log
…

BASH脚本的开头。

优点:您的脚本中有日志定义。适合 Git 等。

于 2016-03-19T14:26:20.863 回答
19

您可以exec稍后使用 command 重定向任何命令的所有 stdout/stderr 输出。

示例脚本:

exec 2> your_file2 > your_file1
your other commands.....
于 2015-04-26T14:32:56.147 回答
17

这可能是标准错误。您可以重定向它:

... > out.txt 2>&1
于 2011-07-13T05:10:45.400 回答
16

命令:

foo >> output.txt 2>&1

附加output.txt文件,而不替换内容。

于 2015-11-24T17:08:01.893 回答
7

用于>>附加:

command >> file

于 2015-04-16T09:38:31.247 回答