How can I exit a batch file from inside a subroutine?
If I use the EXIT command, I simply return to the line where I called the subroutine, and execution continues.
Here's an example:
@echo off
ECHO Quitting...
CALL :QUIT
ECHO Still here!
GOTO END
:QUIT
EXIT /B 1
:END
EXIT /B 0
Output:
Quitting...
Still here!
Update:
This isn't a proper answer, but I ended up doing something along the lines of:
@echo off
CALL :SUBROUTINE_WITH_ERROR || GOTO HANDLE_FAIL
ECHO You shouldn't see this!
GOTO END
:SUBROUTINE_WITH_ERROR
ECHO Simulating failure...
EXIT /B 1
:HANDLE_FAIL
ECHO FAILURE!
EXIT /B 1
:END
ECHO NORMAL EXIT!
EXIT /B 0
The double-pipe statement of:
CALL :SUBROUTINE_WITH_ERROR || GOTO HANDLE_FAIL
is shorthand for:
CALL :SUBROUTINE_WITH_ERROR
IF ERRORLEVEL 1 GOTO HANDLE_FAIL
I would still love to know if there's a way to exit directly from a subroutine rather than having to make the CALLER handle the situation, but this at least gets the job done.
Update #2: When calling a subroutine from within another subroutine, called in the manner above, I call from within subroutines thusly:
CALL :SUBROUTINE_WITH_ERROR || EXIT /B 1
This way, the error propagates back up to the "main", so to speak. The main part of the batch can then handle the error with the error handler GOTO :FAILURE
GOTO :EOF– afrazier Dec 07 '11 at 22:06%~0to the variable instead oftrue:if not "%selfwrapped%"=="%~0" ( set selfwrapped=%~0 .... ). That way you can use the same trick in multiple batch scripts that call each other. – GolezTrol Jul 27 '15 at 20:41Do you think it's worth an edit to explain how it works? It took me a minute to unpack all that and realize it is actually just calling the batch file (
– Sean Sep 19 '17 at 14:07%~0) with all the arguments (%*) from a nested cmd.exe, and the/sis used to control the way the%ComSpec%argument handles the double quotes around the call.