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?
You want:
The syntax
2>&1
will redirect2
(stderr) to1
(stdout). You can also hide messages by redirecting toNUL
, more explanation and examples on MSDN.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 the1>
redirect, otherwise it will not work.Correct way:
dir > a.txt 2>&1
. To append, use>>
.To add the stdout and stderr to the general logfile of a script:
I just chopped out the answer as @Anders just posted it, but...
From my Windows help, I searched on redirection (URL ms-its:C:\WINDOWS\Help\ntcmds.chm::/redirection.htm).
You may want to read about >> and | (pipe), too.
There is, however, no guarantee that the output of SDTOUT and STDERR are interweaved line-by-line in timely order, using the POSIX redirect merge syntax.
If an application uses buffered output, it may happen that the text of one stream is inserted in the other at a buffer boundary, which may appear in the middle of a text line.
A dedicated console output logger (like the "StdOut/StdErr Logger" by 'LoRd MuldeR') may be more reliable for such a task. See: MuldeR's OpenSource Projects
Correct, file handle 1 for the process is STDOUT, redirected by the
1>
or by>
(1 can be omitted, by convention, the command interpreter [cmd.exe] knows to handle that). File handle 2 is STDERR, redirected by2>
.Note that if you're using these to make log files, then unless you're sending the outut to _uniquely_named_ (eg date-and-time-stamped) log files, then if you run the same process twice, the redirected will overwrite (replace) the previous log file.
The
>>
(for either STDOUT or STDERR) will APPEND not REPLACE the file. So you get a cumulative logfile, showwing the results from all runs of the process - typically more useful.Happy trails...