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

后端 未结 3 1552
半阙折子戏
半阙折子戏 2020-12-19 09:50

I am trying to find way to break / exit from FOR loop, if there are any error occured. Below is content of batch file.

@echo on

set myfile=D:\\sample.txt

F         


        
3条回答
  •  南笙
    南笙 (楼主)
    2020-12-19 10:26

    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.

提交回复
热议问题