Redirecting stdout and stderr in a batch file

One thing that I constantly need and can never remember the syntax for is redirecting stdout and stderr in a Windows batch file or cmd script (actually, the syntax is pretty much the same for *nix shell scripts).

Rather than just a one-sentence note here to remind me, I’ll write a few more sentences as explanation. Hopefully this will save someone a little bit of time

For starters, you can redirect the output of a command to a file like so:

blah.exe > output.txt

That example will overwrite any pre-existing output.txt file. If you want to append to the file, use:

blah.exe >> output.txt

But this only redirects “standard output” (stdout). If your program encounters an error, the output generated by the error condition probably won’t show up in the file. If you want it to show up in the file, redirect “standard error” (stderr) also like so:

blah.exe 2>&1 output.txt

At the moment, I can’t tell you if that will append or overwrite. I’ll check that out and update the post…

2 thoughts on “Redirecting stdout and stderr in a batch file

  1. gar

    That last statement will overwrite. If you want to append, use >>:

    blah.exe 2>&1 >>output.txt

    (copy stderr to the stdout handle and send stdout to append to a file.)

    One thing I had a heck of a time finding out how to do is to redirect both stderr and stdout to a pipe. But it turns out it’s pretty much the same thing:

    blah.exe 2>&1 | find “expectederrorstring”
    if errorlevel 1 dosomething

    (copies stderr output to stdout handle and redirects all stdout through the pipe as input to the find command. I then check errorlevel to determine if that expected string was found.)

Leave a Reply

Your email address will not be published. Required fields are marked *