366

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.

0

9 Answers 9

363

Check the errorlevel in an if statement, and then exit /b (exit the batch file only, not the entire cmd.exe process) for values other than 0.

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

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

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! 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.

11
  • 35
    Is there a way to state it once for the entire file? "On error goto" or something similar? Apr 9, 2009 at 15:29
  • 3
    +1 for the negative errorlevel check. Had a script silently fail because of a negative result.
    – devstuff
    Sep 16, 2010 at 4:37
  • 1
    Careful: the enabledelayedexpansion is CRITICAL and also required for an if/else or any other block
    – MarcH
    Apr 4, 2013 at 23:05
  • 2
    Delayed expansion enabled/disabled or command extensions (required for neq) enabled/disabled does not matter on using if not errorlevel 1 exit /B as explained by Microsoft in support article Using command redirection operators and in help output on running if /? in a cmd window. The current errorlevel (exit code) is kept on exiting processing of batch file with exit /B. Note: exit with parameter /B requires enabled command extensions, see Where does GOTO :EOF return to?
    – Mofi
    Jan 13, 2017 at 16:56
  • 3
    Take note that for some commands (e.g. Robocopy) there are some exitcode > 0 that is not really an error ss64.com/nt/robocopy-exit.html Nov 3, 2020 at 9:30
290

Add || goto :label to each line, and then define a :label.

For example, create this .cmd file:

@echo off

echo Starting very complicated batch file...
ping -invalid-arg || goto :error
echo OH noes, this shouldn't have succeeded.
goto :EOF

:error
echo Failed with error #%errorlevel%.
exit /b %errorlevel%

See also question about exiting batch file subroutine.

6
  • 6
    It's a very common idiom in most shell scripting languages, and it reads well: "Do this, or this if it fails.."
    – Fowl
    Nov 30, 2012 at 5:22
  • 6
    I use a SET to keep manually track of the line number: command || (SET ErrorLine=102 && goto :error)
    – SandRock
    Jul 8, 2013 at 14:10
  • 1
    @MarcelValdezOrozco Seems to me that this is what || was created for in the first place. Maybe not goto in particular, but "try, do this on error" as Fowl mentioned. My question is does this work for all non-zero exit codes? Positives only?
    – jpmc26
    Aug 12, 2013 at 22:05
  • 3
    @jpmc26 yes it does, prove it it to yourself - cmd /k exit -1 && echo success || echo fail - prints fail.
    – Fowl
    Aug 12, 2013 at 22:56
  • 5
    You can even avoid the labels with something like command || exit /b %errorlevel% Jul 26, 2016 at 14:16
125

The shortest:

command || exit /b

If you need, you can set the exit code:

command || exit /b 666

And you can also log:

command || echo ERROR && exit /b
2
  • 6
    does exit /b by chance return the original failing exit code? Oct 15, 2015 at 18:54
  • 11
    @FrankSchwieterman, yes, %ERRORLEVEL% is untouched when you call exit /b, so the error code is forwarded Oct 17, 2015 at 7:18
36

Here is a polyglot program for BASH and Windows CMD that runs a series of commands and quits out if any of them fail:

#!/bin/bash 2> nul

:; set -o errexit
:; function goto() { return $?; }

command 1 || goto :error

command 2 || goto :error

command 3 || goto :error

:; exit 0
exit /b 0

:error
exit /b %errorlevel%

I have used this type of thing in the past for a multiple platform continuous integration script.

0
24

One minor update, you should change the checks for "if errorlevel 1" to the following...

IF %ERRORLEVEL% NEQ 0 

This is because on XP you can get negative numbers as errors. 0 = no problems, anything else is a problem.

And keep in mind the way that DOS handles the "IF ERRORLEVEL" tests. It will return true if the number you are checking for is that number or higher so if you are looking for specific error numbers you need to start with 255 and work down.

1
18

I prefer the OR form of command, as I find them the most readable (as opposed to having an if after each command). However, the naive way of doing this, command || exit /b %ERRORLEVEL% is wrong.

This is because batch expands variables when a line is first read, rather than when they are being used. This means that if the command in the line above fails, the batch file exits properly, but it exits with return code 0, because that is what the value of %ERRORLEVEL% was at the start of the line. Obviously, this is undesirable in our script, so we have to enable delayed expansion, like so:

SETLOCAL EnableDelayedExpansion

command-1 || exit /b !ERRORLEVEL!
command-2 || exit /b !ERRORLEVEL!
command-3 || exit /b !ERRORLEVEL!
command-4 || exit /b !ERRORLEVEL!

This snippet will execute commands 1-4, and if any of them fails, it will exit with the same exit code as the failing command did.

2
  • 5
    Your code is correct, but I believe unnecessarily verbose for simple tasks: exit /b with no argument will preserve the errorlevel. Your example could be simplified to command-1 || exit /b -- shorter and no longer requires EnableDelayedExpansion. However, your code does demonstrate valid use of EnableDelayedExpansion, which someone might build upon, for example: command-1 || (echo Error=!errorlevel! && exit /b).
    – Mike Clark
    Apr 8, 2021 at 9:07
  • @MikeClark, I don't think that's correct. I just tested it and only using delayed expansion and error level failed the batch correctly.
    – Leponzo
    Oct 12, 2022 at 19:26
2

We cannot always depend on ERRORLEVEL, because many times external programs or batch scripts do not return exit codes.

In that case we can use generic checks for failures like this:

IF EXIST %outfile% (DEL /F %outfile%)
CALL some_script.bat -o %outfile%
IF NOT EXIST %outfile%  (ECHO ERROR & EXIT /b)

And if the program outputs something to console, we can check it also.

some_program.exe 2>&1 | FIND "error message here" && (ECHO ERROR & EXIT /b)
some_program.exe 2>&1 | FIND "Done processing." || (ECHO ERROR & EXIT /b)
1

No matter how I tried, the errorlevel always stays 0 even when msbuild failed. So I built my workaround:

Build Project and save log to Build.log

SET Build_Opt=/flp:summary;logfile=Build.log;append=true

msbuild "myproj.csproj" /t:rebuild /p:Configuration=release /fl %Build_Opt%

search for "0 Error" string in build log, set the result to var

FOR /F "tokens=* USEBACKQ" %%F IN (`find /c /i "0 Error" Build.log`) DO (
    SET var=%%F
)
echo %var%

get the last character, which indicates how many lines contains the search string

set result=%var:~-1%

echo "%result%"

if string not found, then error > 0, build failed

if "%result%"=="0" ( echo "build failed" )

That solution was inspired by Mechaflash's post at How to set commands output as a variable in a batch file

and https://ss64.com/nt/syntax-substring.html

1
  • 1
    works only for counts lss than ten. Better; for /f %%F in ('type build.log^|find /c /i "0 Error") do set result=%%F. Note: find "0 Error" will also find 10 Errors.
    – Stephan
    Sep 5, 2017 at 18:10
-3
@echo off

set startbuild=%TIME%

C:\WINDOWS\Microsoft.NET\Framework\v3.5\msbuild.exe c:\link.xml /flp1:logfile=c:\link\errors.log;errorsonly /flp2:logfile=c:\link\warnings.log;warningsonly || goto :error

copy c:\app_offline.htm "\\lawpccnweb01\d$\websites\OperationsLinkWeb\app_offline.htm"

del \\lawpccnweb01\d$\websites\OperationsLinkWeb\bin\ /Q

echo Start Copy: %TIME%

set copystart=%TIME%

xcopy C:\link\_PublishedWebsites\OperationsLink \\lawpccnweb01\d$\websites\OperationsLinkWeb\ /s /y /d

del \\lawpccnweb01\d$\websites\OperationsLinkWeb\app_offline.htm

echo Started Build: %startbuild%
echo Started Copy: %copystart%
echo Finished Copy: %TIME%

c:\link\warnings.log

:error

c:\link\errors.log
2
  • 7
    Please add more information to your answer. Just a block of code is not very helpful. Sep 5, 2013 at 23:48
  • Besides not having added any comments, your snippet doesn't look like a good candidate for explaining a functionality: it seems to contain a lot of things that are completely irrelevant to the question. May 28, 2019 at 6:15

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.