In bash "set -e" at the beginning of the script instructs bash to fail the whole script on first failure of any command inside.
How do I do the same for a Windows batch script?
Not directly but you can add the following to every line which has something to execute.
|| goto :error
And then define error, which stops the script.
:error
exit /b %errorlevel%
Tuim's solution works, but it can be made even simpler.
The ERRORLEVEL is already set, so there is no need to GOTO a label that sets the ERRORLEVEL.
You can simply use
yourCommand || exit /b
Note that exit /b will only exit the current subroutine if you are in the middle of a CALL. Your script will have to exit each CALL, layer by layer, until it reaches the root of the script. That will happen automatically as long as you also put the test after each CALL statement
call :label || exit /b
It is possible to force a batch script to exit immediately from any CALL depth. See How can I exit a batch file from within a function? for more info. Be sure to read both answers. The accepted answer has a couple of potentially serious drawbacks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With