简体   繁体   中英

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 ie 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.

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

When your first IF statement is reached, all occurrences of %ERRORLEVEL% are replaced with whatever it currently is (same as 1st exit code).

Use !ERRORLEVEL! and/or !EXITCODE! to get delayed expansion, so that those variables will get expanded later, with up-to-date values as it were.

This requires you to add setlocal enabledelayedexpansion at the top of your script.

Eg

@echo off
setlocal enabledelayedexpansion
set FOO=foo
echo %FOO%
if 1==1 (
   set FOO=bar
   echo %FOO%
   echo !FOO!
)

Produces:

foo
foo
bar

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM