Windows Batch File Math Weirdness
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 "-------------------开发者_StackOverflow社区----------"
)
Use delayed expansion by putting the following line before your loops:
setlocal enabledelayedexpansion enableextensions
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 cmd
expands variables like %foo%
while parsing a command – and a command like if
or for
includes 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 set
includes a description of what goes wrong without delayed expansion and works with it.
精彩评论