What does "2>&1" in a Windows Command Do?
Asked Answered
R

2

16

Doing some maintenance on a script, I found this line:

ping -n 40 127.0.0.1 > NUL 2>&1

I know from this question that everything up to the NUL causes the script to sleep for 39 seconds. But I don't know what the rest of the command does.

What does the 2>&1 do?

Rigobertorigor answered 13/2, 2017 at 18:56 Comment(4)
microsoft.com/resources/documentation/windows/xp/all/proddocs/… "To redirect all of the output, including handle 2 (that is, STDERR), from the ipconfig command to handle 1 (that is, STDOUT), and then redirect the ouput to Output.log, type..."Folio
2> redirects STDERR output, &1 specifies the batch file parameter to use for the file name.Harbard
Related: cmd.exe redirection operators order and positionSchmitt
Possible duplicate of cmd.exe redirection operators order and positionSchmitt
S
14

Decomposing the line

ping -n 40 127.0.0.1

Send 40 ping packets to local host. If there is not any problem the default behaviour is to wait 1 second between packets, so it generates a 39 second delay

>nul   or   1>nul

Redirects anything written to the standard output stream (stream number 1) to the nul device. Anything sent to this device is discarded. The effect is that all the normal output of the ping command is hidden.

2>&1

This redirects anything written to the standard error stream (stream number 2). As in the previous case, this is done to hide output (errors in this case), but instead of directly requesting to write to the nul device (we could have done 2>nul), this syntax requests to send data in the standard error stream to a copy of the handle used in the standard output stream.

Skydive answered 13/2, 2017 at 19:19 Comment(0)
M
1

Note that in cmd, 2>&1 must be last. This will have no effect:

dir foo 2>&1 >out

File Not Found

In powershell, you can have it in either order.

You can also put the errors in a seperate file:

dir foo 2>err >out
Marquand answered 23/8, 2022 at 4:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.