批次:如何在没有标签的情况下退出 for 循环

批次:如何在没有标签的情况下退出 for 循环

这里是否有一个不使用“goto 标签”即可退出 FOR 的命令?

for %%c in (list) do (
 [some code]
 for %%i in (1 1 100) do (
   [some code]
   if [a condition] exit-this-for
   [some code]
   )
rem go here when exit
 [some code]
 )

我讨厌标签!

答案1

即使您讨厌标签,拒绝使用它们也会限制您的选择。我想不出在单个文件中执行此操作的简单方法。如果您不讨厌使用两个批处理文件的想法,您可以执行类似这样的操作。运行a.cmdwill并根据中的任何内容CALL b.cmd执行检查。ERRORLEVELEXIT /Bb.cmd

命令如下:

REM a.cmd  
@ECHO OFF
SET CHECKVAR=10

CALL b.cmd

IF ERRORLEVEL %CHECKVAR% (
    REM go here when exit from b.cmd met condition
    ECHO "B was %CHECKVAR%"
) ELSE (
    REM go here when exit from b.cmd did not meet condition
    ECHO "B was not %CHECKVAR%"
)

命令

REM b.cmd
@ECHO OFF

FOR /L %%A IN (0,1,3) DO (
    ECHO "A: %%A"
    FOR /L %%B IN (0,1,100) DO (
        ECHO "B: %%B"
        REM Do what ever conditional check you like here.
        REM Just need to return some ERRORLEVEL to a.cmd.
        IF %%B==%CHECKVAR% (
            EXIT /B %CHECKVAR%
        )
    )
)

相关内容