简体   繁体   English

bash:与重定向输出混淆

[英]bash: Confusion with redirecting output

When I execute this command (where fail.cpp is a simple program filled with compiler errors), the errors are not output directly on the screen, but, rather, within the fail.out file: 当我执行此命令(fail.cpp是一个充满编译器错误的简单程序)时,错误不会直接在屏幕上输出,而是在fail.out文件中输出:

g++ fail.cpp > fail.out 2>&1

From my introductory understanding of bash, this makes sense: > redirects the program output (stdout, aka 1) to fail.out, while 2>&1 redirects stderr (aka 2) to this new place for stdout, which is the file. 根据我对bash的介绍性理解,这是有道理的: >将程序输出(stdout,又名1)重定向到fail.out,而2>&1会将stderr(又名2)重定向到stdout的新位置,也就是文件。 (?) (?)

But changing the order of the command makes things happen differently: 但是更改命令的顺序会使事情有所不同:

g++ fail.cpp 2>&1 > fail.out

Now, the error messages go directly onto the screen, and fail.out is a blank file. 现在,错误消息直接显示在屏幕上,fail.out是空白文件。

Why is this? 为什么是这样? It seems like the same idea as above: redirect the errors that this command will produce to stdout ( 2>&1 ), and redirect that, in turn, to the fail.out file. 似乎与上述想法相同:将此命令将产生的错误重定向到stdout( 2>&1 ),然后将其重定向到fail.out文件。 Is it an order of operations thing that I am missing? 我想念的是操作命令吗?

2>&1 means "redirect stderr to where stdout is currently connected", and redirections are processed in order from left to right. 2>&1表示“将stderr重定向到当前stdout所连接的位置”,并按从左到右的顺序处理重定向。 So the first one does: 所以第一个这样做:

  1. Redirect stdout to the fail.out file. 将stdout重定向到fail.out文件。
  2. Redirect stderr to stdout's current connection, ie the fail.out file 将stderr重定向到stdout的当前连接,即fail.out文件

The second one does: 第二个是:

  1. Redirect stderr to stdout's current connection, ie the terminal. 将stderr重定向到stdout的当前连接,即终端。
  2. Redirect stdout to the fail.out file. 将stdout重定向到fail.out文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM