M. Bedross
M. Bedross

Reputation: 129

Arithmetic in batch file loop

I am writing a for loop in a batch file, which is to do arithmetic to a variable each iteration. The loop looks like this:

@echo off
setlocal enabledelayedexpansion
SET d=10
echo !d!

for /L %%t IN (0,1,9) DO (
    SET /A d = %d% + 10
    echo !d!
)

The arithmetic only is good for the first iteration. 'd' is to start at 10 and add by ten each time (10 20 30 ...) but it always stops at 20. In the output of the command prompt it will show:

10
20
20
...
20
20

How can I write this so it will add by ten for the entire loop?

Upvotes: 0

Views: 1395

Answers (2)

RGuggisberg
RGuggisberg

Reputation: 4750

Do as @JosefZ says if you need the academic exercise of arithmetic in a loop. If you want to get the same result with less code you can do this.

for /L %%t IN (20,10,110) DO echo %%t

Upvotes: 1

SomethingDark
SomethingDark

Reputation: 14370

You're close, but you missed using delayed expansion in one spot.

Change SET /A d = %d% + 10 to SET /A d = !d! + 10

@echo off
setlocal enabledelayedexpansion
SET d=10
echo !d!

for /L %%t IN (0,1,9) DO (
    SET /A d = !d! + 10
    echo !d!
)

Upvotes: 3

Related Questions