I have a Windows bat file with the following content:
setlocal EnableDelayedExpansion
rem Stop batch script loop if a command failed.
@echo OFF
FOR %%a in (x86 x86_64 armeabi-v7a arm64-v8a) do (
set MY_ANDROID_BUILD_ABI=%%a
FOR %%m in (debug release) DO (
set MY_MODE=%%m
echo !MY_MODE! -^> !MY_ANDROID_BUILD_ABI!
cd D:\dev\libs\QT6.4\android\!MY_MODE!\!MY_ANDROID_BUILD_ABI!
rem some further build commands go here
cmake --build . --parallel && cmake --install .
)
)
it iterates over build configurations and executes multiple commands inside nested loop to build some library.
How to make the script exit the loop and stop execution when an error occurres?
For example, the script should stop if a directory does not exist or cmake
command failed.
Should I add
IF %ERRORLEVEL% NEQ 0 (
echo "Previous command execution failed."
exit %ERRORLEVEL%
)
after each command?
CodePudding user response:
Yes, you need to add some kind of error checking, since cmd doesn't have built-in exceptions. The full solution is to add after each command:
(command)
if ERRORLEVEL 1 (
echo failure message, maybe to some log
exit !ERRORLEVEL!
)
You can use the shorthand suggested in @Gerhard's comment:
(command) || (echo failure message& exit /b !ERRORLEVEL! )
In either case, beware of using %ERRORLEVEL%
, as it's expanded too early. As your code correctly shows, use !ERRORLEVEL!
(which requires setlocal EnabledDelayedExpansion
), or use the special if ERRORLEVEL 1
format.