배치파일의 if 문 안에서 다른 프로그램이나 배치파일 호출한 이후 에러 값을 확인해서 처리해야 할 경우가 있다.

@echo off
cd /d %~dp0

set TEST=true

if "%TEST%" == "true" (
    echo SubTest
    call SubTest.bat
    IF %ERRORLEVEL% NEQ 0 GOTO ERROR
)

echo success
exit /b 0

:ERROR
echo error
call 
exit /b 1

Test.bat 파일의 내용은 위와 같이 작성하고,

echo SubTest.bat returns error
exit /b 1

SubTest.bat는 위와 같이 작성하자.

 

Test.bat를 실행하면,

Error.bat returns error
success

이상하게도 성공이라고 뜬다.

 

이건 if 문 안에서는 변수값이 바로 변경되지 않는 배치파일의 고유의 오래된(?) 특성 때문인데, 이를 해결하는 방법은 크게 2가지가 있다.

 

1.if 문 안에는 코드를 작성하지 말고, goto 명령어를 이용해서 외부 코드 블록에서 작업을 처리하는 방법.

@echo off
cd /d %~dp0

set TEST=true

if not "%TEST%" == "true" (
	goto SKIP_SUBTEST
)

echo SubTest
call SubTest.bat
IF %ERRORLEVEL% NEQ 0 GOTO ERROR

:SKIP_SUBTEST

echo success
exit /b 0

:ERROR
echo error
call 
exit /b 1

2. setlocal enabledelayedexpansion를 정의하고, 느낌표 변수를 사용하는 방법

@echo off
cd /d %~dp0

setlocal enabledelayedexpansion

set TEST=true

if "%TEST%" == "true" (
	echo SubTest
	call SubTest.bat
	IF !ERRORLEVEL! NEQ 0 GOTO ERROR
)

echo success
exit /b 0

:ERROR
echo error
call 
exit /b 1

setlocal enabledelayedexpansion 이라는 걸 먼저 넣어 주고, % 대신 !를 사용한 변수를 사용하면 값을 정상적으로(?) 받아올 수 있다.

SubTest
SubTest.bat returns error
error

 

+ Recent posts