views:

2742

answers:

6

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 .bat file?

+7  A: 

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

Matthew Flaschen
+5  A: 

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 :)

Jon Skeet
A: 

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

c:\> dir
...
c:\> echo %ERRORLEVEL%
dfa
+5  A: 

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

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

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

will never fail...

JesperE
A: 

It does not work for me:

Java class:

public class App {
    public static void main( String[] args ) {
        System.out.println( "Hello World!" );
        System.exit(1);
    }
}

batch script:

"%JAVA_HOME%/bin/java" -cp d:/projects/tests/misc/bin App
set el=%ERRORLEVEL%
echo %el%

output:

Hello World!
0

What am I doing wrong ?

bulgar
what is wrong? you should have started a new question instead of "answering" this with a question (IMO). But the answer is following..
Carlos Heuberger
+1  A: 

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

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

cmd /E:on

or permanently in the registry

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

for more details:

cmd /?

[]]

Carlos Heuberger