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 fil
To add the stdout and stderr to the general logfile of a script:
dir >> a.txt 2>&1
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.
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 by 2>
.
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...
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
In a batch file (Windows 7 and above) I found this method most reliable
Call :logging >"C:\Temp\NAME_Your_Log_File.txt" 2>&1
:logging
TITLE "Logging Commands"
ECHO "Read this output in your log file"
ECHO ..
Prompt $_
COLOR 0F
Obviously, use whatever commands you want and the output will be directed to the text file. Using this method is reliable HOWEVER there is NO output on the screen.
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 (I.e. the "StdOut/StdErr Logger"
by 'LoRd MuldeR'
) may be more reliable for such a task.
See: MuldeR's OpenSource Projects