Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
542 views
in Technique[技术] by (71.8m points)

windows - 如果内循环失败,如何从外循环退出使用批处理脚本(How to exit from outer loop if inner loop is getting failed Using Batch Script)

Can anyone help me to terminate the whole main program if inner loop has any issue using batch command.

(如果内循环使用批处理命令有任何问题,谁能帮助我终止整个主程序。)

Below is my code.

(下面是我的代码。)

Here i need to exit from main outer loop if value found in inner loop is X.

(如果在内部循环中找到的值是X,在这里我需要从主外部循环退出。)

but currently my code is getting exit from inner loop only.

(但目前我的代码仅从内部循环退出。)

For %%A in (alpha beta gamma) DO (
   Echo Outer loop %%A
   Call :inner 
)
Goto :eof

:inner
For %%B in (U V W X Y Z) DO (
   if %%B==X ( exit /b 2 )
   Echo    Inner loop    Outer=%%A Inner=%%B

)
exit /b 1

Output : it should be like below only.

(输出 :仅应如下所示。)

Outer loop alpha
   Inner loop    Outer=alpha Inner=U
   Inner loop    Outer=alpha Inner=V
   Inner loop    Outer=alpha Inner=W
  ask by Ganesh translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You already set an exit code (errorlevel).

(您已经设置了退出代码(错误级别)。)

Just react on it:

(对此做出反应:)

setlocal enabledelayedexpansion
For %%A in (alpha beta gamma) DO (
   Echo Outer loop %%A
   Call :inner 
   if !errorlevel! equ 2 (echo inner loop failed & exit /b 2)
)
Goto :eof

:inner
For %%B in (U V W X Y Z) DO (
   if %%B==X ( exit /b 2 )
   Echo    Inner loop    Outer=%%A Inner=%%B

)
exit /b 1

Aschipfl suggested " Just insert if ErrorLevel 2 goto :EOF after the call command line "

(Aschipfl建议“ if ErrorLevel 2 goto :EOFcall命令行后在if ErrorLevel 2 goto :EOF插入 ”)
That might be a good idea (and avoids delayed expansion), but be aware that if errorlevel 2 actually means "if errorlevel is 2 or higher".

(这可能是一个好主意(并避免延迟扩展),但是请注意, if errorlevel 2实际上表示“如果错误级别为2或更高”。)

If your inner loop only ever returns 0 or 2 , that's definitively the better solution.

(如果您的内部循环仅返回02 ,那肯定是更好的解决方案。)

When it may return more possible errorlevels, you have to use extreme care handling them with if errorlevel .

(当它可能返回更多可能的错误级别时,您必须格外小心处理if errorlevel 。)

(That's the reason, I chose if !errorlevel! instead)

((这就是原因,我选择的if !errorlevel! ))


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...