12

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?

Community
  • 1
  • 1
user2023861
  • 8,030
  • 9
  • 57
  • 86
  • 1
    https://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/redirection.mspx?mfr=true "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..." – ceejayoz Feb 13 '17 at 18:59
  • `2>` redirects STDERR output, `&1` specifies the batch file parameter to use for the file name. – rcgldr Feb 13 '17 at 19:16
  • Related: [cmd.exe redirection operators order and position](http://stackoverflow.com/q/25559389) – aschipfl Feb 13 '17 at 23:59
  • 1
    Possible duplicate of [cmd.exe redirection operators order and position](http://stackoverflow.com/questions/25559389/cmd-exe-redirection-operators-order-and-position) – aschipfl Feb 20 '17 at 07:55

2 Answers2

13

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.

MC ND
  • 69,615
  • 8
  • 84
  • 126
0

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
js2010
  • 23,033
  • 6
  • 64
  • 66