I have a loop in a batch script and I would like to do some arithmetics with the loop counter. I found out how to evaluate expressions, how to add numbers here: http://serverfault.com/questions/60039/evaluating-expressions-in-windows-batch-script

How do I do the same but with variables?

For example:

set x = 100
for /L %%i in (1,1,5) do (
    set Result=0
    set /a Result = %%i+%%x
    echo %Result%
)

As output I would expect

101 102 103 104 105

Thanks!

link|improve this question

67% accept rate
feedback

3 Answers

up vote 4 down vote accepted

You really should move away from Batch files.

@echo off

setlocal enabledelayedexpansion

set x=100
set result=0

for /L %%i in (1,1,5) do (

  set /A result=!x! + %%i

  echo !result!
)

endlocal
link|improve this answer
2  
Yeah. Powershell == good. – squillman Aug 28 '09 at 17:14
But batch files == challenge. And challenges are fun :) – Joey Jan 5 '10 at 23:00
feedback

You are resetting Result to zero at each step. Move that before the loop. Also, try help set at the cmd prompt for more information on all this. Especially look at the section on delayed environment variable expansion.

link|improve this answer
Although yes, it was a glaring error on his part, the problem still can't be solved without using delayed expansion – Izzy Aug 28 '09 at 17:59
That's why I included the sentence that begins "Especially...". – Dennis Williamson Aug 28 '09 at 18:28
feedback

This is not at all working for me.. If i try to give set /a Result = %%i+%%x then i am getting a error " missing operand "

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.