Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a "set -e" for a DOS batch script?

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?

like image 566
mark Avatar asked Dec 13 '12 11:12

mark


2 Answers

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%
like image 141
Tuim Avatar answered Sep 21 '22 22:09

Tuim


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.

like image 39
dbenham Avatar answered Sep 21 '22 22:09

dbenham