I find it an embarrassment when I want to use endlocal
inside an if
/for
statement.
Please check this delayexpe.bat :
@echo off
setlocal EnableDelayedExpansion
set dvar=oldata
if "1" == "1" (
REM Deliberately need a delayed-expansion context
set dvar=newdata
echo [1]=%dvar%
echo [2]=!dvar!
REM I want to set outvar for my calling environment, so I need endlocal.
endlocal & ( set "outvar=!dvar!" )
REM Normally, here will be an `exit /b 0`.
)
echo [3]outvar=%outvar%
exit /b 0
The output is:
[1]=oldata
[2]=newdata
[3]outvar=!dvar!
It means that delayed-expansion syntax !dvar!
does not take effect on the same statement as endlocal
, BUT, I need that endlocal
because I now want to change my parent environment.
Moving endlocal
outside the whole if
block so to use endlocal & ( set "outvar=%some_temp_var%" )
may be a solution, but complicates the code flow.
I just can't figure out the reason why CMD refuse to expand !dvar!
along side with endlocal
. Can anyone clarify this?