Domanda

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:

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

From my introductory understanding of bash, this makes sense: > redirects the program output (stdout, a.k.a. 1) to fail.out, while 2>&1 redirects stderr (a.k.a. 2) to this new place for stdout, which is the file. (?)

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.

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. Is it an order of operations thing that I am missing?

È stato utile?

Soluzione

2>&1 means "redirect stderr to where stdout is currently connected", and redirections are processed in order from left to right. So the first one does:

  1. Redirect stdout to the fail.out file.
  2. Redirect stderr to stdout's current connection, i.e. the fail.out file

The second one does:

  1. Redirect stderr to stdout's current connection, i.e. the terminal.
  2. Redirect stdout to the fail.out file.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top