Exit in For loop - Windows Command Processor (CMD.EXE)

China☆狼群 提交于 2019-12-01 05:43:41

Joey's answer is great. I have used it with success. I discovered that you don't have to exit the script though. You can use goto :SomeLabel, where :SomeLabel is a label outside of the loop.

FOR /F "tokens=1,2 delims=," %%i in (%myfile%) do (
  if defined exit goto :ParseError
  call :process "%%i"
)

@echo SUCCESS: %myfile%
goto :RestOfScript

:ParseError
@echo FAILURE: cannot parse %myfile%
@echo Using defaults...

:RestOfScript
...

You can set a variable, meaning that the complete loop should be aborted and use it like this:

:fail1
echo "Step in fail1"
pause
set exit=1

And you'd change the loop like this:

FOR /F "tokens=1,2 delims=," %%i in (%myfile%) do (
  if defined exit (
    exit /b 9993
  ) else (
    call :process "%%i"
  )
)

(broken into multiple lines for readability).

Since you are just calling a subroutine from the for loop there is no way for this subroutine to exit the loop directly. Hence the workaround with a variable.

SSi

You don't need to call a label

set USBDRIVE=SETLOCAL 
set exit=ENABLEDELAYEDEXPANSION

FOR %%D IN (C D E F G H I J K L M N O P Q R S T U V W X Y Z) DO (
  DIR %%D:\SOURCES\INSTALL.WIM > nul 2>&1 && call set USBDRIVE=%%D: && call set exit=1
  if defined exit goto :dd3
)
:dd3
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!