Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arithmetic inside a for loop batch file

Tags:

batch-file

cmd

I have a for loop in a batch file that looks like this:

for %%y in (100 200 300 400 500) do (
    set /a x = y/25     
    echo %x%
)

The line:

set /a x = y/25

Doesn't seem to be doing any division. What is the correct syntax for dividing each y by 25? I only need the integer result from this division.

like image 311
dr_rk Avatar asked Aug 25 '12 03:08

dr_rk


People also ask

What is %% in a batch file?

Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. ( <set> ) Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.

Can you do math in a batch file?

Note that Windows batch files don't support floating-point arithmetic, so if an expression result is a fractional number, only the integer part will be counted. For example, 3/2 evaluates as 1 and 2/3 as 0. Show activity on this post. DON'T do maths in batch.

Can a batch file take arguments?

Batch scripts support the concept of command line arguments wherein arguments can be passed to the batch file when invoked. The arguments can be called from the batch files through the variables %1, %2, %3, and so on.


2 Answers

Environment variables need not be expanded to use in a SET /A statement. But FOR variables must be expanded.

Also, even if your computation worked, the ECHO would fail because percent expansion takes place when a statement is parsed, and the entire FOR construct is parsed at once. So the value of %x% would be the value as it existed before the loop is executed. To get the value that was set within the loop you should use delayed expansion.

Also, you should remove the space before the assignment operator. You are declaring a variable with a space in the name.

@echo off
setlocal enableDelayedExpansion
for %%A in (100 200 300 400 500) do (
  set n=%%A

  REM a FOR variable must be expanded
  set /a x=%%A/25

  REM an environment variable need not be expanded
  set /a y=n/25

  REM variables that were set within a block must be expanded using delayed expansion
  echo x=!x!, y=!y!

  REM another technique is to use CALL with doubled percents, but it is slower and less reliable
  call echo x=%%x%%, y=%%y%%
)
like image 60
dbenham Avatar answered Sep 17 '22 15:09

dbenham


It's not doing anything because "y" is just a letter. You need percent signs to reference the variable.

set /a x = %%y/25
like image 20
Nilpo Avatar answered Sep 19 '22 15:09

Nilpo