Ebrahimi
Ebrahimi

Reputation: 1239

wrong value of %errorlevel% in nested if in .bat file

I have written a .bat file to first run a program, if it is correctly finished I run another program and check return value of it.

first-program.exe
IF "%ERRORLEVEL%"=="0" (
    second-program.exe
    IF "%ERRORLEVEL%"=="0" (
        ECHO OK
    ) ELSE (
        ECHO NOK
    )
)

However the second %ERRORLEVEL% is always equal to first, it doesn't set to the return value of second-program.exe.

Upvotes: 4

Views: 1865

Answers (1)

hoonose
hoonose

Reputation: 94

Both instances of %ERRORLEVEL% are in the same block of code and thus both get their values at the moment when the first instance is updated. Consider enabling delayed expansion of variables with enabledelayedexpansion and replacing %ERRORLEVEL% with !ERRORLEVEL! to update each instance individually. For instance:

@echo off
setlocal enabledelayedexpansion
first-program.exe
IF "!ERRORLEVEL!"=="0" (
    second-program.exe
    IF "!ERRORLEVEL!"=="0" (
        ECHO OK
    ) ELSE (
        ECHO NOK
    )
)
endlocal

Upvotes: 5

Related Questions