How to set a global variable from inside a loop
How to set a global variable from inside a loop
So here is the batch code I am using.
set fullstring=
set string=testago
echo %string%>x&FOR %%? IN (x) DO SET /A strlength=%%~z? - 2&del x
for /L %%a in (1,1,%strlength%) do (
set b=%%a - 1
set c=%%a
set this=%string:~%%b,%%c%
set fullstring=!fullstring!%this%
)
echo %fullstring%
pause
What this does is read back a string (string) character-by-character to another one (fullstring). I need to know how to overwrite the fullstring from the for loop.
for
set
for /L
for /?
set /?
Is that really your Minimal, Complete, and Verifiable example? Did you fail to show us your
SETLOCAL
command?– jwdonahue
Sep 1 at 18:13
SETLOCAL
Please read How to Ask. The answer to your question probably wouldn't help you with whatever your current problem is. You failed to state exactly what your script is doing as it is written. If it was doing what you intended, you probably wouldn't be asking any questions about it.
– jwdonahue
Sep 1 at 18:15
1 Answer
1
@echo off
setlocal enabledelayedexpansion
set "fullstring="
set "string=testago"
> x echo %string%
for %%? in (x) do set /a "strlength=%%~z? - 2"
del x
for /l %%a in (1,1,%strlength%) do (
set /a "b=%%a - 1"
call set "this=%%string:~!b!,1%%"
set "fullstring=!fullstring!!this!"
)
echo "%fullstring%"
pause
In the for /l
loop, no need for c
variable so removed.
for /l
c
Use of call set
to do a 2nd parse of the line to set this
variable.b
requires delayed expansion then string
variable needs expanding so
use of call set
on string
using doubled percentages achieves this.
call set
this
b
string
call set
string
The 2nd argument of the variable substitution is the length.
Character by character will be a constant 1 for length.
Concatenating the full string will require delayed expansion
or use of call set
as an alternative.
call set
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
I guess, you need to know, how
for
,set
and delayed expanison are working.. The content of yourfor /L
loop doesn't make much sense. Enterfor /?
andset /?
and read their output.– Stephan
Sep 1 at 15:13