tags:

views:

2514

answers:

2

I have a batch file that's calling the same executable over and over with different parameters. How do I make it terminate immediately if one of the calls returns an error code of any level?

Basically, I want the equivalent of MSBuild's ContinueOnError=false.

+6  A: 

Check the errorlevel in an if statement, and then exit /b (exit the batch file only, not the entire cmd.exe process) for values of 1 or greater.

    same-executable-over-and-over.exe /with different "parameters"
    if errorlevel 1 exit /b %errorlevel%
    if %errorlevel% neq 0 exit /b %errorlevel%

If you want the value of the errorlevel to propagate outside of your batch file

    if errorlevel 1 exit /b %errorlevel%
    if %errorlevel% neq 0 exit /b %errorlevel%

but if this is inside a for it gets a bit tricky. You'll need something more like:

    setlocal enabledelayedexpansion
    for %%f in (C:\Windows*) do (
       same-executable-over-and-over.exe /with different "parameters"
       if errorlevel 1 exit /b !errorlevel!
       if !errorlevel! neq 0 exit /b !errorlevel!
    )

Edit: You have to check the error after each command. There's no global "on error goto" type of construct in cmd.exe/command.com batch. I've also updated my code per CodeMonkey, although I've never encountered a negative errorlevel in any of my batch-hacking on XP or Vista.

system PAUSE
Is there a way to state it once for the entire file? "On error goto" or something similar?
Josh Kodroff
+1 for the negative errorlevel check. Had a script silently fail because of a negative result.
devstuff
+1  A: 

@system PAUSE: If the exe crashes, you will mostly likely get a negative error code (e.g. 0xC0000354). It's also not uncommon to 'return -1' from C++ programs.

Why MS decided to make %errorlevel% a signed int I'll never know. Batch has so many hacks for backwards compatibility, it seems strange that they overlooked 'if errorlevel #' in the face of possibly negative results.

Timbo