Page 1 of 1

In for loop, how to pass variable from one setlocal to another

Posted: 25 Apr 2019 15:27
by sincos2007

Code: Select all

:test1
setlocal EnableDelayedExpansion

set "source_bat_file=txt1.txt"
for /f "delims=" %%i in (%source_bat_file%) do (
   rem echo %%i

   setlocal DisableDelayedExpansion
   set "line1=%%i"
   echo 1: %line1%
   endlocal&set line1=%line1%

   setlocal EnableDelayedExpansion
   echo 2: !line1!
   endlocal

   pause
)

endlocal
goto :eof
The first setlocal is for preserve content like !var1! from input text file.

Thanks

Re: In for loop, how to pass variable from one setlocal to another

Posted: 25 Apr 2019 15:53
by aGerman
Wrong way. Keep the FOR loop in an environment with delayed expansion disabled. Define your variable, then enable delayed expansion to output your variable.

Code: Select all

:test1
setlocal DisableDelayedExpansion

set "source_bat_file=txt1.txt"
for /f "delims=" %%i in (%source_bat_file%) do (
   set "line1=%%i"
   
   setlocal EnableDelayedExpansion
   echo !line1!
   endlocal
   
   pause
)

endlocal
goto :eof
Steffen

Re: In for loop, how to pass variable from one setlocal to another

Posted: 25 Apr 2019 16:25
by sincos2007
Will it cause: “reach max recurse of setlocal” error?

Re: In for loop, how to pass variable from one setlocal to another

Posted: 26 Apr 2019 04:47
by dbenham
As long as you include ENDLOCAL for every SETLOCAL within the FOR loop, then the code will work fine without any recursion limit being reached.

But if you forget the ENDLOCAL, then yes, you can get that error.

Re: In for loop, how to pass variable from one setlocal to another

Posted: 30 Apr 2019 14:20
by sincos2007
thanks