apirogov
apirogov

Reputation: 1316

What is wrong with this batch script?

I need a batch that reads a number from a file, increments it and saves it back into this file... This is what I came up with:

@ECHO OFF
SETLOCAL EnableDelayedExpansion

IF EXIST script\BUILDVERSION (
  SET /p input = <script\BUILDVERSION
  SET /a result=%input%+1
  ECHO %result% > script\BUILDVERSION
) ELSE (
  ECHO 0 > script\BUILDVERSION
)

At first it worked in a strange way, the result from reading the number from the file seemed to be a small random number, the result of the sum seemed random too... I don't know what I did, but now it doesn't even read the number from file into the variable...

Thanks in advance for help!

Upvotes: 2

Views: 159

Answers (1)

Instead of %input% and %result%, try using !input! and !result!. This seems to work better when using delayed expansion. Also, make sure you don't have any unnecessary spaces when reading from the file. You'll end up with:

@ECHO OFF
SETLOCAL EnableDelayedExpansion

IF EXIST script\BUILDVERSION (
  SET /p input=<script\BUILDVERSION
  SET /a result=!input!+1
  ECHO !result! > script\BUILDVERSION
) ELSE (
  ECHO 0 > script\BUILDVERSION
)

Upvotes: 4

Related Questions