Adding numbers stored in variables in windows batch script
Solution 1
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
Solution 2
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.
Related videos on Youtube
![raoulsson](https://i.stack.imgur.com/D8nV6.jpg?s=256&g=1)
raoulsson
CTO at Contovista AG Before: CEO at Zorp Technologies Inc., San Francisco, ...until Google Lens came out... Experienced software engineer and teamlead looking to build/enable useful, delightful, and meaningful products. Passionate, hard-worker interested in contributing to team-oriented, strong engineering cultures. Proven track record of hiring and running successful teams.
Updated on September 17, 2022Comments
-
raoulsson almost 2 years
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: 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!
-
squillman almost 15 yearsYeah. Powershell == good.
-
aeroshock almost 15 yearsAlthough yes, it was a glaring error on his part, the problem still can't be solved without using delayed expansion
-
Dennis Williamson almost 15 yearsThat's why I included the sentence that begins "Especially...".
-
Joey over 14 yearsBut batch files == challenge. And challenges are fun :)