简体   繁体   中英

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?

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

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

您还可以使用以下语法而不会延迟扩展:

if errorlevel 1 if not errorlevel 2 ( echo error )

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