Wrong Errorlevel Inside Parenthesis in Windows Batch Script

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

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

Sophia Al-Mansoor
Author

Sophia Al-Mansoor

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.