Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch file Errorlevel issue

I am on Windows 7 Enterprise and calling a jar from batch file which returns 0, 1 or 2 depending on condition, I have used "System.exit" for same,

following is my batch script

@echo off

java -jar "test.jar" %*
set exitcode=%ERRORLEVEL%
echo here is 1st exit code %exitcode%
if %exitcode% == 2 (    
        VERIFY > nul
        set exitcode=%ERRORLEVEL%
        echo here is 2nd exit code after VERIFY %exitcode%
        call test.exe %*
        echo here is 2nd exit code %ERRORLEVEL% 

    if %ERRORLEVEL% == 0    (
           cmd /c "exit /b 0"
           call test1.exe -f
           echo here is 3rd exit code %errorlevel%
    )
)exit /b %errorlevel%

What I am doing in above code is, calling a jar and depending on errorlevel it returns I am calling another exe and again depending on errorlevel of that exe I am calling third exe. Issue is, exitcode I am getting is first exit code assigned i.e. if test.jar exists with 2 even after successful execution of other exes errorlevel doesn't get changed. And third exe never gets executed. Tried different approaches of calling a

cmd exit /b 0

for resetting errorlevel to 0 but its not working.

like image 237
Rahul Borkar Avatar asked Mar 04 '26 14:03

Rahul Borkar


1 Answers

Your problem is that cmd expands environment variables immediately when a statement is parsed, not when it's executed. A statement in this sense includes the whole if including the blocks. You need to use delayed expansion, so stick the following at the start of your batch:

setlocal enabledelayedexpansion

and then use !errorlevel! instead of %errorlevel% within the conditional statement (likewise for exitcode).

like image 90
Joey Avatar answered Mar 07 '26 04:03

Joey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!