Redirect Windows cmd stdout and stderr to a single

2018-12-31 19:42发布

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?

7条回答
君临天下
2楼-- · 2018-12-31 19:53

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.

查看更多
临风纵饮
3楼-- · 2018-12-31 19:56

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

Correct way: dir > a.txt 2>&1. To append, use >>.

查看更多
余欢
4楼-- · 2018-12-31 19:58

To add the stdout and stderr to the general logfile of a script:

dir >> a.txt 2>&1
查看更多
栀子花@的思念
5楼-- · 2018-12-31 20:03

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.

查看更多
刘海飞了
6楼-- · 2018-12-31 20:07

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

查看更多
忆尘夕之涩
7楼-- · 2018-12-31 20:14

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...

查看更多
登录 后发表回答