Calculating the sum of two variables in a batch script

Swarage picture Swarage · May 20, 2012 · Viewed 185.4k times · Source

This is my first time on Stack Overflow so please be lenient with this question. I have been experimenting with programming with batch and using DOSbox to run them on my linux machine.

Here is the code I have been using:

@echo off
set a=3
set b=4
set c=%a%+%b%
echo %c%
set d=%c%+1
echo %d%

The output of that is:

3+4
3+4+1

How would I add the two variables instead of echoing that string?

Answer

staticbeast picture staticbeast · May 20, 2012

You need to use the property /a on the set command.

For example,

set /a "c=%a%+%b%"

This allows you to use arithmetic expressions in the set command, rather than simple concatenation.

Your code would then be:

@set a=3
@set b=4
@set /a "c=%a%+%b%"
echo %c%
@set /a "d=%c%+1"
echo %d%

and would output:

7
8