Why doesn’t this work?
@echo off
for /l %%i in (0, 1, 100) do (
for /l %%j in (0, 1, 10) do (
set /a curr=%%i*10 + %%j
echo %curr%
)
echo "-----------------------------"
)
This is the output I get from this:
1010
1010
1010
1010
1010
1010
1010
1010
1010
1010
1010
"----------------------------"
1010
1010
1010
1010
1010
1010
1010
1010
...
It seems like it precomputes the math before executing, so that when it does finally execute, %curr% is already at 1010. How do I keep it from doing that? I’m trying to get output like this:
0
1
2
3
4
5
6
7
8
9
10
"----------------------------"
11
12
...
Thanks in advance
Answer from Johannes Rössel (for those who might look for it later):
@echo off
setlocal enabledelayedexpansion enableextensions
for /l %%i in (0, 1, 100) do (
for /l %%j in (0, 1, 10) do (
set /a curr=%%i*10+%%j
echo !curr!
)
echo "-----------------------------"
)
Use delayed expansion by putting the following line before your loops:
And then use the environment variable as
!curr!instead of%curr%.You’re changing the contents of an environment variable within a block and use the changed content again in the same block. This can’t work without delayed expansion. The reason is that
cmdexpands variables like%foo%while parsing a command – and a command likeiforforincludes the block that may follow as well. Delayed expansion causes variables to be evaluated right before executing a command which is what you want here.help setincludes a description of what goes wrong without delayed expansion and works with it.