简体   繁体   中英

Batch looping an if statement on the same line

I want to loop the if exist line once so that the line will run continuously until a unused sequential number is found (it has to loop on the same line so it becomes part of the if statement). Is there a better way to achieve this ?

if exist "*%num%*" (set /a num+=jump) 

update

@echo off
set /p usrname=enter folder name 
set /a num=100
set /a jump=10

if exist "*%num%*" (set /a num+=jump) 

MD %num%_%usrname%

What is sounds like you are attempting to do is:

WHILE IF NOT EXIST "*%num%*" SET /A num+=jump

There is no such thing. You have a very limited amount of usable commands to program with in a batch file. Here is all the commands you can use.

What you can do to get it onto 2 lines is this

@echo off
set /p usrname=enter folder name 
set /a num=100
set /a jump=10

:loop
if exist "*%num%*" (set /a num+=jump & GOTO loop)

MD %num%_%usrname%

And if you really want to shorten it up you can use conditional execution. When the directory already exists, increment the number and goto the loop.

@echo off
set /p usrname=enter folder name 
set /a num=100
set /a jump=10

:loop
MD "%num%_%usrname%" 2>nul || (set /a num+=jump & GOTO loop)

How about this?

@echo off
set /p usrname=enter folder name 
set /a num=100
set /a jump=10
:test_exist
if not exist "*%num%*" goto found_one
set /a num+=jump
goto test_exist
:found_one
MD %num%_%usrname%

There's technically a race condition in there, but that will only matter if other people/processes are working in the folder at the same time.

Personally, I'd use

@echo off
set /p usrname=enter folder name 
set /a num=100
set /a jump=10

for /L %%a in (%num%,%jump%,2000000000) do if not exist "*%%a*" set /a num=%%a & MD %%a_%usrname%&goto done
:done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM