0

How can I 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, 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
1
  • Just insert if ErrorLevel 2 goto :EOF after the call command line... Commented Dec 1, 2019 at 11:08

1 Answer 1

1

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"
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 your inner loop only ever returns 0 or 2, that's definitively the better solution. When it may return more possible errorlevels, you have to use extreme care handling them with if errorlevel. (That's the reason, I chose if !errorlevel! instead)

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks Stephen, Just 1 doubt, suppose that if i have multiple inner function so do i need to maintain errorlevel for each inner loop? for e.g. Call :inner1 call :inner2 call :inner3 how to restrict the execution using a single error level if any one got failed?
I don't quite understand. Do you want to break the outer loop as soon as one of the inner loops fails or do you want to execute all inner loops regardless of their success and just know afterward if one of them failed?
I have to break the outer loop if there are multiple inner loop and any one of inner loop fails.
just repeat the two lines call ... and if ... for each inner loop. (when needed, you can change the exit to a goto :error; And of course a label :error somewhere to do something in case of any "inner-loop-error")
(Btw: Any goto will break all loops. So if %%B==X goto :ExitLoops within the inner loop will cancel all currently running loops and jump to the label ExitLoops (instead of returning to the outer loop)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.