重定向Windows中命令提示符的标准输出和错误输出信息

测试遇到Windows guest,依然需要写Windows上的BAT脚本应用于自动化测试中,对于其中执行的程序和脚本,需要将其运行的标准输出和错误输出重定向到文件中,然后执行完成后可以分析该日志文件即可了解执行情况。
其实Windows中关于输出重定向,和Linux中基本上是一样的。
1. 使用“>”符号进行输出重定向,以覆盖的方式重定向到文件。
2. 使用“>>”符号进行输出重定向,是以追加的方式添加到文件的末尾。
3. 用“1>”或者“>”表示重定向标准输出(STDOUT)。
4. 用“2>”表示重定向标准错误输出(STDERR)。
5. 用“2>&1”将标准错误输出重定向到标准输出。
6. 用“nul”表示NUL设备,可以将不需要的输出重定向到NUL中销毁,相当于Linux中的/dev/null设备。

好吧,如下来几个例子吧:

如下参考文档来自微软的官方文档:
http://support.microsoft.com/kb/110930/en-us?fr=1

When redirecting output from an application using the “>” symbol, error messages still print to the screen. This is because error messages are often sent to the Standard Error stream instead of the Standard Out stream.

Output from a console (Command Prompt) application or command is often sent to two separate streams. The regular output is sent to Standard Out (STDOUT) and the error messages are sent to Standard Error (STDERR). When you redirect console output using the “>” symbol, you are only redirecting STDOUT. In order to redirect STDERR you have to specify “2>” for the redirection symbol. This selects the second output stream which is STDERR.
EXAMPLE
The command “dir file.xxx” (where file.xxx does not exist) will display the following output:
Volume in drive F is Candy Cane Volume Serial Number is 34EC-0876

File Not Found
If you redirect the output to the NUL device using “dir file.xxx > nul”, you will still see the error message:
File Not Found
To redirect the error message to NUL, use the following command:

dir file.xxx 2> nul

Or, you can redirect the output to one place, and the errors to another.

dir file.xxx > output.msg 2> output.err

You can print the errors and standard output to a single file by using the “&1” command to redirect the output for STDERR to STDOUT and then sending the output from STDOUT to a file:

dir file.xxx 1> output.msg 2>&1

master

Stay hungry, stay foolish.

One Comment

发表评论

电子邮件地址不会被公开。 必填项已用*标注