Volodymyr Bezuglyy
Volodymyr Bezuglyy

Reputation: 16825

Strange behavior of batch file

I have two cmd files. child.cmd:

@echo off
exit 1

parent.cmd:

@echo off
cmd /C child.cmd
if %errorlevel% EQU 0 (
   echo OK
) else (
   echo ERROR
)

If to run parent.cmd, then ERROR will be printed.

But if a little change parent.cmd, then OK will be printed:

@echo off
if "YES" EQU "YES" (
   cmd /C child.cmd
   if %errorlevel% EQU 0 (
      echo OK
   ) else (
      echo ERROR
   )
)

Why OK is printed in the second example?

Upvotes: 2

Views: 131

Answers (2)

foxidrive
foxidrive

Reputation: 41287

You can also use this syntax without delayed expansion:

if errorlevel 1 if not errorlevel 2 ( echo error )

Upvotes: 1

Endoro
Endoro

Reputation: 37589

inside a code block you need delayed expansion to access %variables%:

 @echo off &setlocal enabledelayedexpansion
 if !errorlevel! EQU 0 (

Upvotes: 5

Related Questions