cmd.exe redirection operators order and position

command 2>&1 1>nul doesn’t work is not correct. It works. But as usual, it does what you asked not what you wanted

From left to right:

  • 2>&1 data to stream 2 (stderr) will be sent to a copy/duplicate of the handle that stream 1 (stdout) is using.

  • 1>nul data to stream 1 will be sent to nul.

The duplicate is the key. Data is not sent to whatever stream 1 points, but to a copy of the stream handle. When stream 1 is redirected, stream 2 has its own handle, a copy of the previous stream 1. Changing stream 1 does not affect stream 2

Now, lets see the working code, from left to right

  • 1>nul Set the handle in stream 1 to point to nul

  • 2>&1 Set the handle in stream 2 to a copy of the handle in use in stream 1, that is, a handle to nul

About position

Most of the time the position (before command, after command or both) is irrelevant. To execute a command, the parser has to first prepare the streams that the command will use. This preparation is done if it is considered necessary (try redirecting rem command input or output) before starting command execution.

The only cases where there is a difference are when what we want to obtain from the command and what the parser understands are not the same. One obvious case is when we need to output a string with an ending digit. Code as

echo 1 2 3>file 

will not send the full string to the target file. 1 2 will be echoed to console, and the data written to stream 3 (nothing in this command) will be sent to file

Of course, a space can be added at the end of the data (between 3 and >), but this space will be included in the output. If this is not acceptable, the solution is to place the redirection at the start of the command

>file echo 1 2 3

Leave a Comment