16

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?

2 Answers 2

17

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.

0
8

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%
1
  • 2
    +1, but there is an even simpler solution. See my answer.
    – dbenham
    Dec 13, 2012 at 15:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.