Is there a way to redirect ONLY stderr to stdout (not combine the two) so it can be piped to other programs?

前端 未结 2 2033
伪装坚强ぢ
伪装坚强ぢ 2020-11-27 16:18

I\'m working in a Windows CMD.EXE environment and would like to change the output of stdout to match that of stderr so that I can pipe

相关标签:
2条回答
  • 2020-11-27 16:34

    From looking at http://support.microsoft.com/kb/110930 it seems that you want 2>&1 1>NUL. So something like the following should work for you:

    test.exe 2>&1 1>NUL | find "someErrorString"
    
    0 讨论(0)
  • 2020-11-27 16:54

    Interesting question :-)

    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 and 3 will contain original definition of stderr, and 2 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>&2 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 Why doesn't my stderr redirection end after command finishes? And how do I fix it? for some really wild adventures with redirection :-)

    0 讨论(0)
提交回复
热议问题