8

This one could turn out as the dumbest question ever, as I am probably missing out the obvious. Anyway, here it is: Can you evaluate expressions in a batch script. For example, I want to add two numbers and print the result:

echo 4+2

This will just print "4+2", not "6". Maybe I am taking batch scripting on windows a little bit too far...

Thanks!

raoulsson
  • 4,763
  • 10
  • 34
  • 29

3 Answers3

9

This way:

Set /a 4+2

Or to store it in a variable for later:

Set /a foo = 4+2
echo %foo%

And to answer your last line, there is a good chance that you may be pushing batch a little further than intended. The Windows Script host is available on your machine and would allow VBScript or JScript. Also if you are going to learn something new anyway I would highly suggest using Powershell instead.

EBGreen
  • 1,453
  • 11
  • 10
3
set Result=0

echo start %Result%

echo Adding 4 and 2
set /a Result= 4+2

echo finish %result%

pause >nul
Izzy
  • 8,224
  • 2
  • 31
  • 35
0

If you have bash/perl installed (eg. cygwin), just call them to do the math:

@for /f "delims=" %%a in ('perl -e "print(%*)"'        ) do @set RESULT=%%a
@echo %RESULT%

@for /f "delims=" %%a in ('bash -c "echo $((%*))"'        ) do @set RESULT=%%a  
@echo %RESULT%

Sample result:

c:\> script.cmd  2**10/3
341.333333333333
341
mosh
  • 111
  • 2