Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading