Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
622 views
in Technique[技术] by (71.8m points)

batch file - How to increment variable under DOS?

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?

question from:https://stackoverflow.com/questions/21697199/how-to-increment-variable-under-dos

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...