如何在 Windows 批处理文件中获取 Java 程序的退出状态

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/887066/
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-08-11 20:41:27  来源:igfitidea点击:

How to get the exit status of a Java program in Windows batch file

javawindowsbatch-fileexit-code

提问by pugmarx

Analogous to the $?in Linux, is there a way to get the exit status of a program in a Windows batch file (.bat)?
Say for example the program has a System.exit(0)upon successful execution, and a System.exit(1)upon a failure, how do I trap these exit values in a .batfile?

$?Linux 中的类似,有没有办法在 Windows 批处理文件 ( .bat) 中获取程序的退出状态?
例如,程序System.exit(0)在成功执行System.exit(1)时有一个,在失败时有一个,我如何将这些退出值捕获到.bat文件中?

采纳答案by Matthew Flaschen

Use %ERRORLEVEL%. Don't you love how batch files are clear and concise? :)

使用%ERRORLEVEL%。您不喜欢批处理文件的简洁明了吗?:)

回答by Jon Skeet

Something like:

就像是:

java Foo
set exitcode=%ERRORLEVEL%
echo %exitcode%

It's important to make this the absolute next line of the batch file, to avoid the error level being overwritten :)

将其作为批处理文件的绝对下一行很重要,以避免错误级别被覆盖:)

Note that if you use the

请注意,如果您使用

IF ERRORLEVEL number

"feature" of batch files, it means "if the error level is greater than or equal to number" - it's not based on equality. I've been bitten by that before now :)

批处理文件的“特征”,这意味着“如果错误级别大于或等于number” - 它不是基于相等性。我以前被那个咬过:)

回答by dfa

Most of the usual external command operations return ERRORLEVEL0 and this usually (but NOT invariably) indicates that no error was encountered:

大多数常用的外部命令操作返回ERRORLEVEL0,这通常(但并非总是)表示没有遇到错误:

c:\> dir
...
c:\> echo %ERRORLEVEL%

回答by JesperE

Raymond Chen has a good blog post named ERRORLEVEL is not %ERRORLEVEL%. Worth checking out.

Raymond Chen 有一篇名为ERRORLEVEL is not %ERRORLEVEL%的好博文。值得一试。

Also worth noting is that the REM command which most people think of as comments, really aren't. The REM command is a nop command which always succeeds. After a REM, the error level is always 0. So

另外值得注意的是,大多数人认为是注释的 REM 命令实际上不是。REM 命令是一个总是成功的 nop 命令。在 REM 之后,错误级别始终为 0。所以

willalwaysfail.bat
REM unless you insert a comment after it
if errorlevel 1 goto fail

will never fail...

永远不会失败...

回答by user85421

mostly answering bulgar's question, but complementing the other answers:

主要回答bulgar的问题,但补充了其他答案:

for %ERRORLEVEL% to work you need to have the command extensionsactivated in Windows (it's the default).
For one session:

要使 %ERRORLEVEL% 工作,您需要在 Windows 中激活命令扩展(这是默认设置)。
对于一个会话:

cmd /E:on

or permanently in the registry

或永久在注册表中

 HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\EnableExtensions = 0x01

for more details:

更多细节:

cmd /?

[]]

[]]