Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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!

share|improve this question
add comment

2 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
share|improve this answer
2  
Yeah. Powershell == good. –  squillman Aug 28 '09 at 17:14
    
But batch files == challenge. And challenges are fun :) –  Јοеу Jan 5 '10 at 23:00
add comment

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.

share|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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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