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

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
sincos2007
Posts: 36
Joined: 05 Apr 2019 05:52

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

#1 Post by sincos2007 » 25 Apr 2019 15:27

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

aGerman
Expert
Posts: 3605
Joined: 22 Jan 2010 18:01
Location: Germany

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

#2 Post by aGerman » 25 Apr 2019 15:53

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

sincos2007
Posts: 36
Joined: 05 Apr 2019 05:52

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

#3 Post by sincos2007 » 25 Apr 2019 16:25

Will it cause: “reach max recurse of setlocal” error?

dbenham
Expert
Posts: 2218
Joined: 12 Feb 2011 21:02
Location: United States (east coast)

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

#4 Post by dbenham » 26 Apr 2019 04:47

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.


Post Reply