Skip to content

Instantly share code, notes, and snippets.

@davidruhmann
Created July 26, 2013 02:45
Show Gist options
  • Save davidruhmann/6085703 to your computer and use it in GitHub Desktop.
Save davidruhmann/6085703 to your computer and use it in GitHub Desktop.
[Batch] Output Tips and Tricks by Dave Benham
CMD processes redirection from left to right. You want to first redirect 2 (stderr) to &1 (stdout), then redirect 1 (stdout) to something else. At this point stderr will still be redirected to the previous definition of stdout. The pipe will still work with the old definition of stdout (which now contains stderr).
If you don't care about stdout then you can redirect to nul
program.exe 2>&1 1>nul | find " "
If you want to capture stdout to a file then redirect to a file
program.exe 2>&1 1>yourFile | find " "
If you still want to see stdout on the console, but you only want to pipe stderr to FIND, then you can redirect 1 to con:
program.exe 2>&1 1>con: | find " "
Note that there is a subtle difference between the original definition of stdout and con:. For example, cls >con: does not clear the screen, it prints a funny character to the screen instead.
It is possible to truly swap stdout and stderr if you use a 3rd (initially unused) file handle. 1 will contain original definition of stderr, and both 2 and 3 will contain original definition of stdout.
program.exe 3>&2 2>&1 1>&3 | find " "
Actually there is an additional file handle defined every time a redirection is performed. The original definition is saved in the first available unused file handle. Assume there has not been any redirection prior to issuing the above command. 3>&1 does not save the original definition of 3 because 3 was not previously defined. But 2>&1 saves the original definition of stderr in 4 (3 has already been used), and 1>&2 saves the original definition of stdout in 5.
So technically, the explicit redirection of 3 is not needed to swap stderr and stdout
program.exe 2>&1 1>&3 | find " "
2>&1 saves stderr in 3 and 2 is redirected to &1 (stdout). 1>&3 saves stdout in 4 and 1 is redirected to &3 (stderr).
But the above will only work properly if you are positive that 3 has not already been defined prior to issuing the command. It is much safer to explicitly define 3 as in my prior code example.
See How to permanently redirect standard error back to the console again? for some really wild adventures with redirection :-)
@davidruhmann
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment