要将stderr和stdout合并到stdout流中,我们将其附加到命令中:
2>&1
例如,查看编译g++main.cpp时的前几个错误:
g++ main.cpp 2>&1 | head
2>&1的详细含义是什么?
要将stderr和stdout合并到stdout流中,我们将其附加到命令中:
2>&1
例如,查看编译g++main.cpp时的前几个错误:
g++ main.cpp 2>&1 | head
2>&1的详细含义是什么?
当前回答
要将stdout重定向到file.txt:
echo test > file.txt
这相当于:
echo test 1> file.txt
要将stderr重定向到file.txt:
echo test 2> file.txt
所以>是将流重定向到另一个文件描述符的语法(&I):
0是标准输入1是标准输出2是标准错误
要将stdout重定向到stderr:
echo test 1>&2 # equivalently, echo test >&2
要将stderr重定向到stdout:
echo test 2>&1
因此,在2>&1中:
2> 将stderr重定向到(未指定)文件。&1将stderr重定向到stdout。
其他回答
注意,1>&2不能与2>&1互换使用。
假设您的命令依赖于管道,例如:docker日志1b3e97c49e39 2>&1|grep“一些日志”grepping将在stderr和stdout之间发生,因为stderr基本上被合并到stdout中。
但是,如果您尝试:docker日志1b3e97c49e39 1>&2|grep“一些日志”,grepping根本不会在任何地方搜索,因为Unix管道通过连接stdout|stdin来连接进程,而在第二种情况下,stdout被重定向到stderr,Unix管道对此没有兴趣。
该构造将标准错误流(stderr)发送到标准输出(stdout)的当前位置——其他答案似乎忽略了这个货币问题。
您可以使用此方法将任何输出句柄重定向到另一个,但它最常用于将stdout和stderr流引导到单个流中进行处理。
例如:
# Look for ERROR string in both stdout and stderr.
foo 2>&1 | grep ERROR
# Run the less pager without stderr screwing up the output.
foo 2>&1 | less
# Send stdout/err to file (with append) and terminal.
foo 2>&1 |tee /dev/tty >>outfile
# Send stderr to normal location and stdout to file.
foo >outfile1 2>&1 >outfile2
请注意,最后一个命令不会将stderr重定向到outfile2,而是将其重定向到遇到参数时的stdout(outfile1),然后将stdout重定向到outile2。
这允许一些相当复杂的诡计。
要将stdout重定向到file.txt:
echo test > file.txt
这相当于:
echo test 1> file.txt
要将stderr重定向到file.txt:
echo test 2> file.txt
所以>是将流重定向到另一个文件描述符的语法(&I):
0是标准输入1是标准输出2是标准错误
要将stdout重定向到stderr:
echo test 1>&2 # equivalently, echo test >&2
要将stderr重定向到stdout:
echo test 2>&1
因此,在2>&1中:
2> 将stderr重定向到(未指定)文件。&1将stderr重定向到stdout。
这些数字表示文件描述符(fd)。
零是标准输入一个是标准输出二是标准错误
2> &1将fd 2重定向为1。
如果程序使用任何数量的文件描述符,这都适用。
如果忘记了,可以查看/usr/include/unistd.h:
/* Standard file descriptors. */
#define STDIN_FILENO 0 /* Standard input. */
#define STDOUT_FILENO 1 /* Standard output. */
#define STDERR_FILENO 2 /* Standard error output. */
也就是说,我已经编写了C工具,这些工具使用非标准文件描述符进行自定义日志记录,因此除非将其重定向到文件或其他文件,否则您不会看到它。
如果系统上不存在/foo,而/tmp确实存在…
$ ls -l /tmp /foo
将打印/tmp的内容并为/foo打印错误消息
$ ls -l /tmp /foo > /dev/null
将/tmp的内容发送到/dev/null并为/foo打印错误消息
$ ls -l /tmp /foo 1> /dev/null
将完全相同(注意1)
$ ls -l /tmp /foo 2> /dev/null
将打印/tmp的内容并将错误消息发送到/dev/null
$ ls -l /tmp /foo 1> /dev/null 2> /dev/null
将向/dev/null发送列表和错误消息
$ ls -l /tmp /foo > /dev/null 2> &1
是速记