Home > Blockchain >  How to Increment a number in the name of a file everytime the Batch file is run
How to Increment a number in the name of a file everytime the Batch file is run

Time:12-25

I am using CommandCam, a software which takes a photo from specified webcam everytime it is run. I am using it to take a photo whenever my computer starts up, but what the software does is it overwrites the previous image taken with the same name. So I created a .bat file that checks if image.bmp exists, save the new image file as image_1.bmp. However it doesn't seem to work.

I have tried to use GOTO but it doesn't work.

@echo off
if exist image.bmp (goto existing) else (goto nonexisting)

:nonexisting
set /A imgnum = 0
.\CommandCam.exe
exit /B

:existing
set /A imgnum =1
.\CommandCam.exe /filename image_%imgnum%.bmp
exit /B

The first time the .bat is run, it works as expected. A image.bmp file is created. And next time the .bat is run, it works too, A image_1.bmp is created. But the third and so on time the .bat is run, it doesn't work and just overwrites image_1.bmp . Any Help?

CodePudding user response:

The batch file should check image.bmp, image1.bmp, image2.bmp, etc. until it finds a non-existing file. Like this:

@echo off
setlocal
set imgnum=
if not exist image.bmp goto nonexisting
set imgnum=0

:existing
set /A imgnum  = 1
if exist image%imgnum%.bmp goto existing

:nonexisting
echo >image%imgnum%.bmp
endlocal

The setlocal/endlocal make sure the environment isn't left with imagnum set to some value. I just used echo to create the file for testing.

  • Related