如何在Bash中将stderr重定向到stdout
source link: https://www.myfreax.com/bash-redirect-stderr-stdout/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
将命令的输出重定向到文件或将其通过管道传递到另一个命令时,您可能会注意到错误消息已打印在屏幕上。
在Bash和其他Linux Shell中,执行程序时,它使用三个标准I/O流。 每个流由一个数字文件描述符表示:
0
-stdin
,标准输入流。1
-stdout
,标准输出流。2
-stderr
,标准错误流。
文件描述符只是代表打开文件的数字。
输入流通常通过在键盘上输入来向程序提供信息。
程序输出进入标准输出流,错误消息进入标准错误流。 默认情况下,输入流和错误流都打印在屏幕上。
重定向标准输出流
重定向是一种从程序捕获输出并将其作为输入发送到另一个程序或文件的方法。
流可以使用n>
运算符重定向,其中n
是文件描述符。
省略n
时,默认为标准输出流1
。 例如,以下两个命令是相同的; 两者都会将命令输出(stdout
)重定向到文件。
command > file
command 1> file
要重定向标准错误流(stderr
),请使用2>
运算符:
command 2> file
您可以将stderr
和stdout
都写到两个单独的文件中:
command 2> error.txt 1> output.txt
要禁止在屏幕上显示错误消息,请将stderr
重定向到/dev/null
:
command 2> /dev/null
将stderr
重定向到stdout
将程序的输出保存到文件中时,通常会将stderr
重定向到stdout
,以便将所有内容都保存在一个文件中。
要将stderr
重定向到stdout
并将错误消息发送到与标准输出相同的文件,请使用以下命令:
command > file 2>&1
> file
将stdout
重定向到file
,2>&1
将stderr
重定向到stdout
的当前位置。
重定向的顺序很重要。 例如,以下示例仅将stdout
重定向到file
。 以下这种情况是因为stderr
重定向到stdout
,然后stdout
重定向到了file
。
command 2>&1 > file
将stderr
重定向到stdout
的另一种方法是使用&>
构造。 在Bash中,&>
与2>&1
的含义相同:
command &> file
在命令行上工作时,了解重定向和文件描述符的概念非常重要。
要重定向stderr
和stdout
,请使用2>&1
或&>
构造。
如果您有任何问题或反馈,请随时发表评论。
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK