Exiting a batch from a function
Posted: 02 Mar 2016 07:39
Hi,
I found here detail D.Benham's analysis showing that exiting a batch from withing a function by adding a syntax error has bad side effects, because the fatal syntax error terminates batch processing without the implicit ENDLOCAL! I seems to experience random errors in my project due to this fact. Trying to find a SHORT code allowing to exit a batch from a function correctly.
Some folks posted short code snippets to this effect. One was offered by Max Suslov:
The other by Charles Godwin:
Can someone explain, if and why these solutions allow to terminate the batch cleanly as suggested by their authors, as opposed to terminating by introducing a syntax error? Unfortunately, the above suggestions were not commented by batch experts, but they seem to offer elegant solutions - correct
I found here detail D.Benham's analysis showing that exiting a batch from withing a function by adding a syntax error has bad side effects, because the fatal syntax error terminates batch processing without the implicit ENDLOCAL! I seems to experience random errors in my project due to this fact. Trying to find a SHORT code allowing to exit a batch from a function correctly.
Some folks posted short code snippets to this effect. One was offered by Max Suslov:
Code: Select all
@echo off
:: comment next line if you want to export any local variables in caller environment
setlocal
set FLAG=1
rem Do something
call :interactive_check
set FLAG2=2
rem Do something
call :interactive_check
goto :eof
:interactive_check
if errorlevel 1 (
echo.
echo /!\/!\/!\/!\/!\/!\/!\/!\/!\/!\/!\/!\/!\
echo Error in compilation process... exiting
echo /!\/!\/!\/!\/!\/!\/!\/!\/!\/!\/!\/!\/!\
(goto) 2>nul & endlocal & exit /b %ERRORLEVEL%
) else (
echo Continuing to next step
)
goto :eof
The other by Charles Godwin:
Code: Select all
@echo off
call :error message&if errorlevel 1 exit /b %errorlevel%<
@echo continuing
exit /b 0
:error
@echo in %0
@echo message: %1
set yes=
set /p yes=[no]^|yes to continue
if /i "%yes%" == "yes" exit /b 0
exit /b 1
Can someone explain, if and why these solutions allow to terminate the batch cleanly as suggested by their authors, as opposed to terminating by introducing a syntax error? Unfortunately, the above suggestions were not commented by batch experts, but they seem to offer elegant solutions - correct