[英]How to get the exit status of a Java program in Windows batch file
Analogous to the $?
类似于$?
in Linux, is there a way to get the exit status of a program in a Windows batch file ( .bat
)? 在Linux中,有没有一种方法可以获取Windows批处理文件( .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 .bat
file? 假设该程序在成功执行时具有System.exit(0)
,在失败时具有System.exit(1)
,如何将这些退出值捕获在.bat
文件中?
Use %ERRORLEVEL% . 使用%ERRORLEVEL% 。 Don't you love how batch files are clear and concise? 您不喜欢批处理文件清晰明了吗? :) :)
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. 批处理文件的“功能”,它表示“如果错误级别大于或等于number
”,则它不是基于相等性。 I've been bitten by that before now :) 我之前一直被那咬伤:)
Raymond Chen has a good blog post named ERRORLEVEL is not %ERRORLEVEL% . Raymond Chen的一篇不错的博客文章ERRORLEVEL不是%ERRORLEVEL% 。 Worth checking out. 值得一试。
Also worth noting is that the REM command which most people think of as comments, really aren't. 还值得注意的是,大多数人认为REM命令不是注释。 The REM command is a nop command which always succeeds . REM命令是始终成功的nop命令。 After a REM, the error level is always 0. So REM之后,错误级别始终为0。因此
willalwaysfail.bat
REM unless you insert a comment after it
if errorlevel 1 goto fail
will never fail... 永远不会失败...
mostly answering bulgar 's question, but complementing the other answers: 主要回答bulgar的问题,但补充其他答案:
for %ERRORLEVEL% to work you need to have the command extensions activated in Windows (it's the default). 为了使%ERRORLEVEL%正常工作,您需要在Windows中激活命令扩展名 (默认设置)。
For one session: 对于一个会话:
cmd /E:on
or permanently in the registry 或永久在注册表中
HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\EnableExtensions = 0x01
for more details: 更多细节:
cmd /?
[]] []]
Most of the usual external command operations return ERRORLEVEL 0 and this usually (but NOT invariably) indicates that no error was encountered: 大多数通常的外部命令操作都返回ERRORLEVEL 0,这通常(但并非总是如此)指示未遇到错误:
c:\> dir
...
c:\> echo %ERRORLEVEL%
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.