I want to start a process with a batch file and if it returns nonzero, do something else. I need the correct syntax for that.
Something like this:
::x.bat
@set RetCode=My.exe
@if %retcode% is nonzero
handleError.exe
As a bonus, you may consider answering the following questions, please :)
- How to write a compound statement with
if
? - If the application
My.exe
fails to start because some DLL is missing will my if work? If not, how can I detect thatMy.exe
failed to start?
ERRORLEVEL
will contain the return code of the last command. Sadly you can only check>=
for it.Note specifically this line in the MSDN documentation for the
If
statement:So to check for 0 you need to think outside the box:
Or if you want to code error handling first:
Further information about BAT programming: http://www.ericphelps.com/batch/ Or more specific for Windows
cmd
: MSDN using batch filesThis is not exactly the answer to the question, but I end up here every time I want to find out how to get my batch file to exit with and error code when a process returns an nonzero code.
So here is the answer to that:
You can write a compound statement in an if block using parenthesis. The first parenthesis must come on the line with the if and the second on a line by itself.
The project I'm working on, we do something like this. We use the
errorlevel
keyword so it kind of looks like:That seems to work for us. Note that you can put in multiple commands in the parens like an echo or whatever. Also note that build_fail is defined as: