How to increment variable under DOS?

shadowz1337 picture shadowz1337 · Feb 11, 2014 · Viewed 144.6k times · Source

I've spent the past 3hrs trying to work this out but just couldn't find a solution. Here's my batch script:

if NOT Exist Counter.txt GOTO START
Type c:\counter.txt
if %COUNTER% EQU %Cycles% goto Pass
if NOT %COUNTER% EQU %Cycles% goto Cycle

:START
Set COUNTER=0
set CYCLES=250

:Cycle
set /A COUNTER=%COUNTER%+1     <----------- PROBLEM
echo Iteration %COUNTER% of %CYCLES%
echo Delay 3 seconds to reboot
choice /cy /n /t:y,3
warmboot.com

:Pass
pause

What it's doing is it runs the file "warmboot.com" (which reboots my PC) and runs for 250 cycles. Once the cycles have run 250 times (i.e when counter equals cycles) then it stops.

Under Windows, this works. However, this doesn't work under DOS environment. I've tried versions from v4 all the way up to v6.22 and even v7 and they all fail when it reaches the "PROBLEM" line.

If I do this:

set /A COUNTER=%COUNTER%+1
echo %Counter%

OR this:

set /A COUNTER+=1
echo %Counter%

both will return a blank line, i.e it shows nothing as the output.

If I type:

set /?

then it shows this:

Displays, sets, or removes cmd.exe environment variables.

SET [variable=[string]]

variable Specifies the environment-variable name.
string Specifies a series of characters to assign to the variable.

but typing the same command under CMD in Windows shows a lot more stuff. I'm thinking that the SET function under DOS doesn't support arithmetic functions, but for work purposes I have to run my scripts in DOS only.

Any ideas?

Answer

Furr picture Furr · Sep 2, 2014

I realize you've found another answer - but the fact is that your original code was nearly correct but for a syntax error.

Your code contained the line

set /A COUNTER=%COUNTER%+1

and the syntax that would work is simply...

set /A COUNTER=COUNTER+1

See http://ss64.com/nt/set.html for all the details on the SET command. I just thought I'd add this clarification for anyone else who doesn't have the option of using FreeDOS.