In a batch script that I am working on, a variable value is not being retained after calling 2 subroutines, one from another from a batch script’s FOR loop.
Here is a code snippet demo’ing the scenario:
set ERRORCODE=0
FOR ... do (
call :myRoutine
@ECHO %ERRORCODE% // Here I am expecting the ERRORCODE to be a 1 (non-zero), but I am seeing that it is getting reset to 0
)
myRoutine:
call :another
IF %ERRORCODE% NEQ 0 GOTO :EOF // Here I am getting the ERRORCODE as 1 as expected
...
GOTO :EOF
another:
something went wrong here..
IF %ERRORLEVEL% NEQ 0 (
set ERRORCODE=1
GOTO :EOF
)
The ERRORCODE is retained just fine – you are just not accessing it properly.
Your problem is that
%ERRORCODE%is expanded when the line is parsed, and the entire parenthesized block of code is parsed all at once, before the FOR loop is executed. So you are seeing the value that existed before the loop is executed.The solution is to use delayed expansion,
!ERRORCODE!, which requiressetlocal enableDelayedExpansion. Delayed expansion occurs when the line is executed. TypeHELP SETorSET /?from the command line for more information about delayed expansion.