要将stderr和stdout合并到stdout流中,我们将其附加到命令中:

2>&1

例如,查看编译g++main.cpp时的前几个错误:

g++ main.cpp 2>&1 | head

2>&1的详细含义是什么?


当前回答

该构造将标准错误流(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。

这允许一些相当复杂的诡计。

其他回答

文件描述符1是标准输出(stdout)。文件描述符2是标准错误(stderr)。

首先,2>1可能是将stderr重定向到stdout的好方法。然而,它实际上会被解释为“将stderr重定向到名为1的文件”。

&指示后面和前面的是文件描述符,而不是文件名。因此,我们使用2>&1。考虑>&成为重定向合并运营商。

该构造将标准错误流(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。

这允许一些相当复杂的诡计。

从程序员的角度来看,这意味着:

dup2(1, 2);

请参见手册页。

了解2>&1是副本也解释了为什么。。。

command >file 2>&1

…与…不同。。。

command 2>&1 >file

第一个将两个流发送到文件,而第二个将错误发送到stdout,并将普通输出发送到文件。

unix命令2>&1

这用于将错误打印到终端。

当产生错误时,它们将被写入内存地址&2的“标准错误”缓冲区,以及来自该缓冲区的2个引用和流。当产生输出时,它们被写入“标准输出”缓冲区的内存地址&1,以及来自该缓冲区的1个引用和流。

所以回到指挥部。每当程序unix_commands产生错误时,它都会将其写入错误缓冲区。因此,我们创建一个指向缓冲区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。