Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect Windows cmd stdout and stderr to a single file

I'm trying to redirect all output (stdout + stderr) of a DOS command to a single file:

C:\>dir 1> a.txt 2> a.txt The process cannot access the file because it is being used by another process. 

Is it possible, or should I just redirect to two separate files?

like image 958
ripper234 Avatar asked Sep 14 '09 11:09

ripper234


People also ask

How do I redirect stderr and stdout to a file in Windows?

You can redirect stderr to stdout by using 2>&1 , and then pipe stdout into grep . what does &1 means? To specify redirection to existing handles, use the ampersand & character followed by the handle number that you want to redirect (that is, &handle# ).

How do I redirect stderr and stdout to a file?

Understanding the concept of redirections and file descriptors is very important when working on the command line. To redirect stderr and stdout , use the 2>&1 or &> constructs.

How do I redirect in CMD?

On a command line, redirection is the process of using the input/output of a file or command to use it as an input for another file. It is similar but different from pipes, as it allows reading/writing from files instead of only commands. Redirection can be done by using the operators > and >> .


2 Answers

You want:

dir > a.txt 2>&1 

The syntax 2>&1 will redirect 2 (stderr) to 1 (stdout). You can also hide messages by redirecting to NUL, more explanation and examples on MSDN.

like image 185
Anders Lindahl Avatar answered Sep 19 '22 13:09

Anders Lindahl


Anders Lindahl's answer is correct, but it should be noted that if you are redirecting stdout to a file and want to redirect stderr as well then you MUST ensure that 2>&1 is specified AFTER the 1> redirect, otherwise it will not work.

REM *** WARNING: THIS WILL NOT REDIRECT STDERR TO STDOUT **** dir 2>&1 > a.txt 
like image 43
DelboyJay Avatar answered Sep 21 '22 13:09

DelboyJay