Is it possible to pull variable out of setlocal and endlocal pair in for loop

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

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

Is it possible to pull variable out of setlocal and endlocal pair in for loop

#1 Post by sincos2007 » 07 May 2019 13:55

Code: Select all

:test5
setlocal DisableDelayedExpansion

set /a "n=0"
for /f "delims=" %%i in (txt1.txt) do (
	set "line=%%i"

	setlocal EnableDelayedExpansion
	set "str_out=!str_out! / number{!n!}-{!line!}"
	rem debug
	echo !str_out!
	endlocal&set "str_out_1=%str_out%"

	set /a "n+=1"

	echo Position 1:
	echo str_out_1=%str_out_1%
)

echo Position 2:
echo str_out_1=%str_out_1%

endlocal
goto :eof
I always feel there has a way to reach this title, without help of io redirection. I believe for loop is powerful.

Eureka!
Posts: 136
Joined: 25 Jul 2019 18:25

Re: Is it possible to pull variable out of setlocal and endlocal pair in for loop

#2 Post by Eureka! » 29 Jul 2019 09:21

Assuming this is an XY-problem:

Easiest way that I know is replacing the for ... DO ( <lots of commands> ) with:
for ... DO call :label.

That will even get rid of the setlocal/endlocal pair.
I didn't understand what you were trying to accomplish, but this should give you some inspiration:

Code: Select all

@echo off
setlocal


   set /a "n=0"
   for /f "delims=" %%i in (lijst.txt) do call :LINE "%%i"

:: Show vars
   set str_out
goto :EOF


::______________________________________________
::
		:LINE
::______________________________________________
::
   set line=%~1
   set str_out_%n%=/ number{%n%}-{%line%}
   set str_out=%str_out% / number{%n%}-{%line%}
   set /a "n+=1"
goto :eof
OUTPUT:

Code: Select all

str_out= / number{0}-{texta} / number{1}-{textb} / number{2}-{textc}
str_out_0=/ number{0}-{texta}
str_out_1=/ number{1}-{textb}
str_out_2=/ number{2}-{textc}
call :LINE "%%i" passes the current line as a parameter to the :LINE routine.
Inside the :LINE routine it is available as %1
Wrap parameters in "" (because of spaces and "dangerous" characters); unwrap them in the :LINE routine.


EDIT: forgot to show the 'lijst.txt' inputfile:

Code: Select all

texta
textb
textc

Post Reply