4

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.

aschipfl
  • 33,626
  • 12
  • 54
  • 99
Ebrahimi
  • 1,209
  • 8
  • 15
  • 1
    Did you try it using delayed expansion? – Compo May 15 '18 at 11:06
  • 2
    You need [delayed expansion](http://ss64.com/nt/delayedexpansion.html) for the `ErrorLevel` after `second-program.exe` as it is updated in the same block of code... – aschipfl May 15 '18 at 11:11
  • 4
    Possible duplicate of [ERRORLEVEL vs %ERRORLEVEL% vs exclamation mark ERRORLEVEL exclamation mark](https://stackoverflow.com/questions/42967840/errorlevel-vs-errorlevel-vs-exclamation-mark-errorlevel-exclamation-mark) – aschipfl May 15 '18 at 11:15
  • 2
    Depending upon the 'programs', you may just be able to do this `"First-Program.exe" && ( "Second-Program.exe" && ( Echo OK ) || Echo NOK )` – Compo May 15 '18 at 14:43

1 Answers1

5

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
hoonose
  • 84
  • 5
  • I only had a single instance of `%ERRORLEVEL%` in my script, and it was incorrectly returning 0. I changed it to `!ERRORLEVEL!` and my script seems to work now. Though I'm still not exactly sure why. The `enabledelayedexpansion` setting is quite ambiguous to me at this moment. – velkoon Feb 15 '23 at 00:59
  • 1
    @velcoon, this can't be answered for sure without seeing your code, but guess that the probable reason can be that you have %ERRORLEVEL% inside an IF or FOR cycle. To be on the safe side, better always use delayed expansion inside cycles. – hoonose Feb 17 '23 at 11:01