Sunday, June 26, 2016

Redirecting stdout and stderr under Windows

Introduction

A console program (i.e. a program that is executed from the command line) can write its output on two separate streams: stdout and stderr. Theoretically stdout is used to display the program results and stderr is used to write error messages.

In a normal execution text written on both the stdout and the stderr isdisplayed on the console.

Lets try with an example. The following simplistic C# code writes a message on stdout and another message in stderr.



using System;
namespace TestStdout
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Error.WriteLine("STDERR message");
            Console.Out.WriteLine("STDOUT message");
        }
    }
}


If we execute this program on the windows command line we get



D:\test>TestStdout.exe
STDERR message
STDOUT message

D:\test>

Redirection

The redirection of stdout and stderr is well known by Linux users but strangely not so much popular for Windows users. However, it works (nearly) the same way with both operating systems

Redirect stdout to a file

To redirect the program output (stdout) to a file, use the operator >



D:\test>TestStdout.exe >out.txt
STDERR message

D:\test>type out.txt
STDOUT message

D:\test>

To get rid of stdout you may redirect it to a special file called NUL that throws away anything sent to it. (note that in Linux it is called /dev/null).



D:\test>TestStdout.exe >NUL
STDERR message

D:\test>


Redirect stderr to a file

To redirect the stderr you use the operator 2>



D:\test>TestStdout.exe 2>err.txt
STDOUT message

D:\test>type err.txt
STDERR message

D:\test>


You may also redirect stderr to NUL if you want to get rid of it



D:\test>TestStdout.exe  2>NUL
STDOUT message


D:\test>

Redirect both stdout and stderr to a file

You may combine > and 2> to redirect both stdout and stderr



D:\test>TestStdout.exe >out.txt 2>err.txt


D:\test>

It is also possible to redirect both stdout and stderr to the same file by using 2>&1 to first redirect stderr to stdout (&1 is in fact stdout) and redirect stdout to a file.



D:\test>TestStdout.exe >OutAndErr.txt 2>&1


D:\test>type OutAndErr.txt
STDERR message
STDOUT message


D:\test>

Redirecting to the clipboard

On Windows sytsems, it is possible to redirect directly to the clipboard instead of redirecting to a file (thank yo to Scott Hanselman for this trick ) by using | clip

You can redirect stdout to the clipboard



D:\test>TestStdout.exe |clip
STDERR message


D:\test>

You can redirect both stdout and stderr to the clipboard by first redirecting stderr to stdout



D:\test>TestStdout.exe 2>&1 |clip


D:\test>

You can redirect only stderr to the clipboard

But this is tricky: you have to redirect stderr to stdout and stdout  to null and pipe to clip. Warning swapping the operations does not get the correct result.


D:\test>TestStdout.exe 2>&1 >NUL |clip


D:\test>