Wrong errorlevel inside parenthesis in Windows batch script

Here is a windows .bat file:

@echo off
call :label
echo %errorlevel%
pause >nul
exit
:label
exit /b 1

Works as expected and outputs 1.

but on changing the code to:

@echo off
if 1==1 ( call :label echo %errorlevel% )
pause >nul
exit
:label
exit /b 1

the output is 0 instead of 1.

The if 1==1 is just to show the result but I need to use another if statement in the actual script. Why is this happening and what is the solution? If delayed expansion is the solution, how to use it?

1 Answer

If delayed expansion is the solution, how to use it?

As follows:

@echo off
setlocal enabledelayedexpansion
if 1==1 ( call :label echo !errorlevel! )
pause >nul
endlocal
exit
:label
exit /b 1

Delayed Expansion will cause variables within a batch file to be expanded at execution time rather than at parse time, this option is turned on with the SETLOCAL EnableDelayedExpansion command.

Source: - EnableDelayedExpansion - Windows CMD - SS64.com

You need to replace % with ! to take advantage of delayed expansion.


Further Reading

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like