Windows 批处理脚本:将所有输出重定向到文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15346863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 10:20:49  来源:igfitidea点击:

Windows Batch Script: Redirect ALL output to a file

windowsbatch-filedacapo

提问by Nicolas

I am running various Java benchmarks and would like to archive the results. I execute the (dacapo) benchmark like this:

我正在运行各种 Java 基准测试并希望将结果存档。我像这样执行(dacapo)基准测试:

C:\VM\jre\bin\java  -jar C:\benchmarks\dacapo-9.12-bach.jar %arg1% > %time::=%

I pass the type of benchmark in over a parameter, thats what %arg1% is.

我通过一个参数传递了基准的类型,这就是 %arg1% 。

You can see that I am redirecting the output to a textfile. Unfortunately, the first and last line of the output is still printed in the console and not into the textfile:

您可以看到我正在将输出重定向到一个文本文件。不幸的是,输出的第一行和最后一行仍然打印在控制台中,而不是打印到文本文件中:

===== DaCapo 9.12 luindex starting =====
===== DaCapo 9.12 luindex PASSED in 2000 msec =====

Especially the last line would be important to have in the text file :)

特别是最后一行在文本文件中很重要:)

Is there a trick to force this behavior?

有什么技巧可以强迫这种行为吗?

回答by Zach Riggle

You must redirect STDOUTand STDERR.

您必须重定向STDOUTSTDERR

command > logfile 2>&1

command > logfile 2>&1

STDINis file descriptor #0, STDOUTis file descriptor #1 and STDERRis file descriptor #2.
Just as "command > file" redirects STDOUTto a file, you may also redirect arbitrary file descriptors to each other. The >&operator redirects between file descriptors. So, 2 >& 1redirects all STDERRoutput to STDOUT.

STDIN是文件描述符#0,STDOUT是文件描述符#1,STDERR是文件描述符#2。
正如“command > file”将STDOUT重定向到文件一样,您也可以将任意文件描述符重定向到彼此。该>&运营商文件描述符之间重定向。因此,2 >& 1将所有STDERR输出重定向到STDOUT

Furthermore, take care to add 2>&1at the end of the instruction because on Windows, the order of redirection is important as command 2>&1 > logfilewill produce an empty file, as Dawid added in the comments.

此外,注意2>&1在指令的末尾添加,因为在 Windows 上,重定向的顺序很重要,因为它command 2>&1 > logfile会产生一个空文件,正如 Dawid 在评论中添加的那样。

回答by Squeezy

Add 2>&1 to your command:

将 2>&1 添加到您的命令中:

 C:\VM\jre\bin\java  -jar C:\benchmarks\dacapo-9.12-bach.jar %arg1% 2>&1 > %time::=% 

This will redirect STDERR to STDOUT which is then redirected into your textfile.

这会将 STDERR 重定向到 STDOUT,然后将其重定向到您的文本文件中。