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
.
Nakilon
34.9k14 gold badges107 silver badges142 bronze badges
asked Apr 9, 2009 at 14:56
Josh KodroffJosh Kodroff
27.3k27 gold badges95 silver badges148 bronze badges
0
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.
answered Apr 9, 2009 at 15:03
system PAUSEsystem PAUSE
37.1k20 gold badges62 silver badges59 bronze badges
11
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.
answered Jan 22, 2012 at 21:58
6
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
answered Feb 20, 2014 at 15:26
Benoit BlanchonBenoit Blanchon
13.4k4 gold badges73 silver badges82 bronze badges
2
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.
answered Oct 18, 2017 at 14:55
Erik AronestyErik Aronesty
11.7k5 gold badges64 silver badges44 bronze badges
0
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.
answered Apr 9, 2009 at 15:30
1
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.
answered Aug 17, 2018 at 14:20
XarnXarn
3,4701 gold badge21 silver badges43 bronze badges
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)
answered Nov 26, 2014 at 6:06
Amr AliAmr Ali
3,0501 gold badge16 silver badges11 bronze badges
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
answered Sep 5, 2017 at 15:13
1
@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
answered Sep 5, 2013 at 23:27
2
Как сделать обработку исключений в CMD?
В python например так:
try:
...
print("Ошибок нет! ")
except:
print("Ошибка!")
-
Вопрос задан
-
617 просмотров
КОМАНДА1 && КОМАНДА2
— вторая команда выполняется, если первая завершилась без ошибок.
КОМАНДА1 || КОМАНДА2
— вторая команда выполняется, если первая завершилась с ошибкой.
КОМАНДА && echo Ошибок нет! || echo Ошибка!
(Для объединения нескольких команд в составную можно использовать скобки, переносы строк или знак &
между командами в одной строке. Для размещения одной простой команды на нескольких строках можно использовать ^
в конце переносимой строки…)
Пригласить эксперта
-
Показать ещё
Загружается…
VK
•
Москва
от 200 000 до 500 000 ₽
ЛАНИТ
•
Санкт-Петербург
от 80 000 ₽
21 сент. 2023, в 10:41
5000 руб./за проект
21 сент. 2023, в 10:18
1000 руб./за проект
21 сент. 2023, в 09:45
1000 руб./за проект
Минуточку внимания
Every scripting and programming language contains an error handler like Java contains try-catch
for error handling. In a Batch script, there is no direct way to do this, but we can create an error handler in the Batch script using a built-in variable of the Batch script name %ERRORLEVEL%
.
This article will show how we can create a Batch script to handle errors and failures. Also, we are going to some examples that make the topic easier.
Error Handling in Batch Script
When a command successfully executes, it always returns an EXIT CODE
that indicates whether the command successfully executed or failed to execute. So, to create an error handling in a Batch file, we can use that EXIT CODE
in our program.
You can follow below general format to create an error handler:
@Echo off
SomeCommand && (
ECHO Message for Success
) || (
ECHO Message for Failure or Error
)
We can also do that by checking the variable named %ERRORLEVEL%
. If the variable contains a value not equal to 0
, then there might be a problem or error when executing the command. To test the %ERRORLEVEL%
variable, you can follow the below example codes:
@ECHO off
Some Command Here !!!
IF %ERRORLEVEL% NEQ 0 (Echo Error found when running the command &Exit /b 1)
You must note that the keyword NEQ
means Not Equal. And the variable %ERRORLEVEL%
will only contain a non-zero value if there is a problem or error in the code.
An Example That Contains Errors
Below, we shared an example. We will run a Batch file named Your_file.bat
from a location.
We intentionally removed that file from the directory. So it’s an error command.
The code for our example will be:
@echo off
ECHO Running a Batch file
CD G:\BATCH\
CALL Your_file.bat
IF errorlevel 1 GOTO ERROR
ECHO The file run successfully.
GOTO EOF
:ERROR
ECHO The file didn't run successfully.
CMD /k
EXIT /b 1
:EOF
Now, as the file doesn’t exist in the directory, it will show an error, and you will get the below output when you run the code shared above.
Output:
Running a Batch file
The system cannot find the path specified.
'Your_file.bat' is not recognized as an internal or external command,
operable program or batch file.
The file didn't run successfully.
An Error-Free Code Example That Runs Successfully
In the example above, we made a mistake on the code intentionally to understand how the code works. If we correct it like below:
@echo off
ECHO Running a Batch file
CALL "G:\BATCH\Yourfile.bat"
IF errorlevel 1 GOTO ERROR
ECHO The file runs successfully.
GOTO EOF
:ERROR
ECHO The file didn't run successfully.
CMD /k
EXIT /b 1
:EOF
Then we will get an output like this:
Running a Batch file
This is from the first file
The file runs successfully.
Remember, all commands we discussed here are only for the Windows Command Prompt or CMD environment.
I have a .bat file in windows that does three things
cmd1 arg1 arg2
cmd2 arg3
cmd3 arg4 arg5 arg6
Sometimes cmd1 can fail and that’s fine, I would like to carry on and execute cmd2 and cmd3. But my bat stops at cmd1. How can I avoid this?
Update for clarity — these are not other .bat files, they are exe commands. Hopefully I don’t have to build a tree of .bat files just to achieve this.
asked Jan 3, 2013 at 22:16
ConfusedNoobConfusedNoob
8572 gold badges12 silver badges18 bronze badges
2
Another option is to use the amperstand (&
)
cmd1 & cmd2 & cmd3
If you use a double, it only carries on if the previous command completes successfully (%ERRORLEVEL%==0
)
cmd1 && cmd2 && cmd3
If you use a double pipe (||
), it only runs the next command if the previous completes with an error code (%ERRORLEVEL% NEQ 0
)
cmd1 || cmd2 || cmd3
answered Jan 3, 2013 at 22:35
Canadian LukeCanadian Luke
24.2k39 gold badges118 silver badges171 bronze badges
10
This worked for me:
cmd.exe /c cmd1 arg1
cmd2
...
This uses cmd.exe
to execute the command in a new instance of the Windows command interpreter, so a failed command doesn’t interrupt the batch script. The /c
flag tells the interpreter to terminate as soon as the command finishes executing.
cmd2
executes even if the first command fails. See cmd /?
from Windows Command Prompt for more information.
answered Dec 4, 2015 at 19:41
Joseph238Joseph238
3212 silver badges5 bronze badges
Presumming the cmds are other .bat files stack the commands like this:
call cmd1
call cmd2
call cmd3
answered Jan 3, 2013 at 22:21
mdpcmdpc
4,4299 gold badges28 silver badges36 bronze badges
To add to Canadian Luke’s answer, if you want to keep your script a little more organized you can use ^
to continue the command chain in a new line in your script, like this:
scoop install windows-terminal & ^
scoop install joplin & ^
scoop install neovim & ^
scoop install autohotkey & ^
... & ^
scoop update -a
Instead of the ugly
scoop install windows-terminal & scoop install joplin & scoop install neovim & ...
answered Jul 7 at 9:47
exicexic
4695 silver badges9 bronze badges
You must log in to answer this question.
Not the answer you’re looking for? Browse other questions tagged
.
Not the answer you’re looking for? Browse other questions tagged
.
- Overview
- Part 1 – Getting Started
- Part 2 – Variables
- Part 3 – Return Codes
- Part 4 – stdin, stdout, stderr
- Part 5 – If/Then Conditionals
- Part 6 – Loops
- Part 7 – Functions
- Part 8 – Parsing Input
- Part 9 – Logging
- Part 10 – Advanced Tricks
Computers are all about 1’s and 0’s, right? So, we need a way to handle when some condition is 1, or else do something different
when it’s 0.
The good news is DOS has pretty decent support for if/then/else conditions.
Checking that a File or Folder Exists
IF EXIST "temp.txt" ECHO found
Or the converse:
IF NOT EXIST "temp.txt" ECHO not found
Both the true condition and the false condition:
IF EXIST "temp.txt" (
ECHO found
) ELSE (
ECHO not found
)
NOTE: It’s a good idea to always quote both operands (sides) of any IF check. This avoids nasty bugs when a variable doesn’t exist, which causes
the the operand to effectively disappear and cause a syntax error.
Checking If A Variable Is Not Set
IF "%var%"=="" (SET var=default value)
Or
IF NOT DEFINED var (SET var=default value)
Checking If a Variable Matches a Text String
SET var=Hello, World!
IF "%var%"=="Hello, World!" (
ECHO found
)
Or with a case insensitive comparison
IF /I "%var%"=="hello, world!" (
ECHO found
)
Artimetic Comparisons
SET /A var=1
IF /I "%var%" EQU "1" ECHO equality with 1
IF /I "%var%" NEQ "0" ECHO inequality with 0
IF /I "%var%" GEQ "1" ECHO greater than or equal to 1
IF /I "%var%" LEQ "1" ECHO less than or equal to 1
Checking a Return Code
IF /I "%ERRORLEVEL%" NEQ "0" (
ECHO execution failed
)
<< Part 4 – stdin, stdout, stderr
Part 6 – Loops >>