There is one exceptionally simple technique that may work, depending on which commands are executed, and another slightly more complex technique that will always work.
1) Simple solution that may or may not work, depending on the commands
Some internal commands only set the ERRORLEVEL if and only if there was an error, and some always set the ERRORLEVEL upon success or error. External commands always set the ERRORLEVEL.
So if all of your commands are internal commands that do not clear the ERRORLEVEL upon success, then you can simply clear the ERRORLEVEL at the start, and then run each command in succession. The ERRORLEVEL will only be non-zero (indicating an error) if any one of the commands failed. You can simply issue EXIT /B
at the end, and the current ERRORLEVEL will be returned.
An arcane but quick way to clear the ERRORLEVEL to 0 at the start is to use (call )
- the trailing space is critical.
(call )
internalCommand1
internalCommand2
...
internalCommandN
exit /b
A list of internal commands that can work with this solution may be found at Which cmd.exe internal commands clear the ERRORLEVEL to 0 upon success?. Again, for this solution to work, you want the internal commands that do not clear the ERRORLEVEL upon success.
2) Slightly more complex solution that always works
Just as with your current solution, you set your own error variable to 0 at the start, and conditionally set it to non zero upon error after each command. But instead of using if errorlevel 1
or if %errorlevel% neq 0
, you can use the conditional ||
command concatenation operator, which only executes the command if the preceding one failed.
set "err=0"
anyCommand1 || set "err=1"
anyCommand2 || set "err=1"
...
anyCommandN || set "err=1"
exit /b %err%