Exit batch with error

Overview Part 1 – Getting Started Part 2 – Variables Part 3 – Return Codes Part 4 – stdin, stdout, stderr Part 5 – If/ …
  • 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

Today we’ll cover return codes as the right way to communicate the outcome of your script’s execution to the world. Sadly, even
skilled Windows programmers overlook the importance of return codes.

Return Code Conventions

By convention, command line execution should return zero when execution succeeds and non-zero when execution fails. Warning messages
typically don’t effect the return code. What matters is did the script work or not?

Checking Return Codes In Your Script Commands

The environmental variable %ERRORLEVEL% contains the return code of the last executed program or script. A very helpful feature is
the built-in DOS commands like ECHO, IF, and SET will preserve the existing value of %ERRORLEVEL%.

The conventional technique to check for a non-zero return code using the NEQ (Not-Equal-To) operator of the IF command:

IF %ERRORLEVEL% NEQ 0 (
  REM do something here to address the error
)

Another common technique is:

IF ERRORLEVEL 1 (
  REM do something here to address the error
)

The ERRORLEVEL 1 statement is true when the return code is any number equal to or greater than 1. However, I don’t use this technique because
programs can return negative numbers as well as positive numbers. Most programs rarely document every possible return code, so I’d rather explicity
check for non-zero with the NEQ 0 style than assuming return codes will be 1 or greater on error.

You may also want to check for specific error codes. For example, you can test that an executable program or script is in your PATH by simply
calling the program and checking for return code 9009.

SomeFile.exe
IF %ERRORLEVEL% EQU 9009 (
  ECHO error - SomeFile.exe not found in your PATH
)

It’s hard to know this stuff upfront – I generally just use trial and error to figure out the best way to check the return code of the program or
script I’m calling. Remember, this is duct tape programming. It isn’t always pretty, but, it gets the job done.

Conditional Execution Using the Return Code

There’s a super cool shorthand you can use to execute a second command based on the success or failure of a command. The first program/script must
conform to the convention of returning 0 on success and non-0 on failure for this to work.

To execute a follow-on command after sucess, we use the && operator:

SomeCommand.exe && ECHO SomeCommand.exe succeeded!

To execute a follow-on command after failure, we use the || operator:

SomeCommand.exe || ECHO SomeCommand.exe failed with return code %ERRORLEVEL%

I use this technique heavily to halt a script when any error is encountered. By default, the command processor will continue executing
when an error is raised. You have to code for halting on error.

A very simple way to halt on error is to use the EXIT command with the /B switch (to exit the current batch script context, and not the command
prompt process). We also pass a specific non-zero return code from the failed command to inform the caller of our script about the failure.

SomeCommand.exe || EXIT /B 1

A simliar technique uses the implicit GOTO label called :EOF (End-Of-File). Jumping to EOF in this way will exit your current script with
the return code of 1.

SomeCommand.exe || GOTO :EOF

Tips and Tricks for Return Codes

I recommend sticking to zero for success and return codes that are positive values for DOS batch files. The positive values are a good idea
because other callers may use the IF ERRORLEVEL 1 syntax to check your script.

I also recommend documenting your possible return codes with easy to read SET statements at the top of your script file, like this:

SET /A ERROR_HELP_SCREEN=1
SET /A ERROR_FILE_NOT_FOUND=2

Note that I break my own convention here and use uppercase variable names – I do this to denote that the variable is constant and should not
be modified elsewhere. Too bad DOS doesn’t support constant values like Unix/Linux shells.

Some Final Polish

One small piece of polish I like is using return codes that are a power of 2.

SET /A ERROR_HELP_SCREEN=1
SET /A ERROR_FILE_NOT_FOUND=2
SET /A ERROR_FILE_READ_ONLY=4
SET /A ERROR_UNKNOWN=8

This gives me the flexibility to bitwise OR multiple error numbers together if I want to record numerous problems in one error code.
This is rare for scripts intended for interactive use, but, it can be super helpful when writing scripts you support but you don’t
have access to the target systems.

@ECHO OFF
SETLOCAL ENABLEEXTENSIONS

SET /A errno=0
SET /A ERROR_HELP_SCREEN=1
SET /A ERROR_SOMECOMMAND_NOT_FOUND=2
SET /A ERROR_OTHERCOMMAND_FAILED=4

SomeCommand.exe
IF %ERRORLEVEL% NEQ 0 SET /A errno^|=%ERROR_SOMECOMMAND_NOT_FOUND%

OtherCommand.exe
IF %ERRORLEVEL% NEQ 0 (
    SET /A errno^|=%ERROR_OTHERCOMMAND_FAILED%
)

EXIT /B %errno%

If both SomeCommand.exe and OtherCommand.exe fail, the return code will be the bitwise combination of 0x1 and 0x2, or decimal 3. This return code tells
me that both errors were raised. Even better, I can repeatedly call the bitwise OR with the same error code and still interpret which errors were
raised.


<< Part 2 – Variables


Part 4 – stdin, stdout, stderr >>

Break Statement Implementation

The break statement is used to alter the flow of control inside loops within any programming language. The break statement is normally used in looping constructs and is used to cause immediate termination of the innermost enclosing loop.

Источник

/* steve jansen */

// another day in paradise hacking code and more

Windows Batch Scripting: Return Codes

Today we’ll cover return codes as the right way to communicate the outcome of your script’s execution to the world. Sadly, even skilled Windows programmers overlook the importance of return codes.

Return Code Conventions

By convention, command line execution should return zero when execution succeeds and non-zero when execution fails. Warning messages typically don’t effect the return code. What matters is did the script work or not?

Checking Return Codes In Your Script Commands

The environmental variable %ERRORLEVEL% contains the return code of the last executed program or script. A very helpful feature is the built-in DOS commands like ECHO , IF , and SET will preserve the existing value of %ERRORLEVEL% .

The conventional technique to check for a non-zero return code using the NEQ (Not-Equal-To) operator of the IF command:

Another common technique is:

The ERRORLEVEL 1 statement is true when the return code is any number equal to or greater than 1. However, I don’t use this technique because programs can return negative numbers as well as positive numbers. Most programs rarely document every possible return code, so I’d rather explicity check for non-zero with the NEQ 0 style than assuming return codes will be 1 or greater on error.

You may also want to check for specific error codes. For example, you can test that an executable program or script is in your PATH by simply calling the program and checking for return code 9009.

It’s hard to know this stuff upfront – I generally just use trial and error to figure out the best way to check the return code of the program or script I’m calling. Remember, this is duct tape programming. It isn’t always pretty, but, it gets the job done.

Conditional Execution Using the Return Code

There’s a super cool shorthand you can use to execute a second command based on the success or failure of a command. The first program/script must conform to the convention of returning 0 on success and non-0 on failure for this to work.

To execute a follow-on command after sucess, we use the && operator:

To execute a follow-on command after failure, we use the || operator:

I use this technique heavily to halt a script when any error is encountered. By default, the command processor will continue executing when an error is raised. You have to code for halting on error.

A very simple way to halt on error is to use the EXIT command with the /B switch (to exit the current batch script context, and not the command prompt process). We also pass a specific non-zero return code from the failed command to inform the caller of our script about the failure.

A simliar technique uses the implicit GOTO label called :EOF (End-Of-File). Jumping to EOF in this way will exit your current script with the return code of 1.

Tips and Tricks for Return Codes

I recommend sticking to zero for success and return codes that are positive values for DOS batch files. The positive values are a good idea because other callers may use the IF ERRORLEVEL 1 syntax to check your script.

I also recommend documenting your possible return codes with easy to read SET statements at the top of your script file, like this:

Note that I break my own convention here and use uppercase variable names – I do this to denote that the variable is constant and should not be modified elsewhere. Too bad DOS doesn’t support constant values like Unix/Linux shells.

Some Final Polish

One small piece of polish I like is using return codes that are a power of 2.

This gives me the flexibility to bitwise OR multiple error numbers together if I want to record numerous problems in one error code. This is rare for scripts intended for interactive use, but, it can be super helpful when writing scripts you support but you don’t have access to the target systems.

If both SomeCommand.exe and OtherCommand.exe fail, the return code will be the bitwise combination of 0x1 and 0x2, or decimal 3. This return code tells me that both errors were raised. Even better, I can repeatedly call the bitwise OR with the same error code and still interpret which errors were raised.

Posted by Steve Jansen Mar 1 st , 2013 batch, scripting, shell, windows

Hi, I’m Steve. I’m a software developer loving life in Charlotte, NC, an (ISC) 2 CSSLP and an avid fan of Crossfit.

And, no, I’m not Steve Jansen the British jazz drummer, though that does sound like a sweet career.

Guides

Recent Posts

Social Stuff

  • @steve-jansen on GitHub
  • @steve-jansen on StackOverflow
  • @steve-jansen ProTips on Coderwall
  • @steve-jansen on Microsft Connect
  • @steve-jansen on ASP.NET User Voice
  • Subscribe via RSS

Copyright © 2015 — Steve Jansen — Powered by Octopress

Источник

Пакетный скрипт – Код возврата

По умолчанию, когда выполнение командной строки завершено, оно должно либо возвращать ноль, если выполнение завершается успешно, либо ненулевое, если выполнение не выполняется. Когда пакетный скрипт возвращает ненулевое значение после сбоя выполнения, ненулевое значение будет указывать, что такое номер ошибки. Затем мы будем использовать номер ошибки, чтобы определить ее причину и соответствующим образом ее устранить.

Ниже приведены общий код выхода и их описание.

Недостаточно виртуальной памяти.

Это указывает на то, что в Windows не хватает памяти.

Код ошибки Описание
Программа успешно завершена.
1 Неверная функция. Указывает, что Action попытался выполнить нераспознанную команду в командной строке Windows cmd.exe.
2 Система не может найти указанный файл. Указывает, что файл не может быть найден в указанном месте.
3 Система не может найти указанный путь. Указывает, что указанный путь не может быть найден.
5 В доступе отказано. Указывает, что у пользователя нет прав доступа к указанному ресурсу.
Программа не распознается как внутренняя или внешняя команда, работающая программа или пакетный файл. Указывает, что команда, имя приложения или путь были введены с ошибкой при настройке действия.
Приложение прекращено в результате CTRL + C. Указывает, что приложение было прекращено либо с помощью клавиш ввода CTRL + C или CTRL + Break, либо с помощью окна командной строки пользователя.
Приложение не удалось правильно инициализировать. Указывает, что приложение было запущено на рабочем столе, к которому у текущего пользователя нет прав доступа. Другая возможная причина – не удалось инициализировать gdi32.dll или user32.dll.

Недостаточно виртуальной памяти.

Это указывает на то, что в Windows не хватает памяти.

Уровень ошибки

Переменная среды% ERRORLEVEL% содержит код возврата последней выполненной программы или сценария.

По умолчанию способ проверки на наличие ОШИБКИ находится через следующий код.

Синтаксис

Обычно используется команда EXIT / B% ERRORLEVEL% в конце пакетного файла, чтобы вернуть коды ошибок из пакетного файла.

EXIT / B в конце командного файла остановит выполнение командного файла.

Используйте EXIT / B в конце пакетного файла для возврата пользовательских кодов возврата.

Переменная среды% ERRORLEVEL% содержит последний уровень ошибки в пакетном файле, который является последними кодами ошибок из последней выполненной команды. В пакетном файле всегда рекомендуется использовать переменные среды вместо постоянных значений, поскольку одна и та же переменная расширяется до разных значений на разных компьютерах.

Давайте посмотрим на быстрый пример того, как проверить коды ошибок из командного файла.

пример

Давайте предположим, что у нас есть пакетный файл с именем Find.cmd, который имеет следующий код. В коде мы четко упомянули, что если мы не найдем файл lists.txt, то должны установить уровень ошибки равным 7. Точно так же, если мы видим, что переменная userprofile не определена, мы должны установить код уровня ошибки на 9.

Давайте предположим, что у нас есть еще один файл с именем App.cmd, который сначала вызывает Find.cmd. Теперь, если Find.cmd возвращает ошибку, в которой он устанавливает уровень ошибки больше 0, он завершает работу программы. В следующем пакетном файле после вызова Find.cnd он на самом деле проверяет, не превышает ли уровень ошибки больше 0.

Выход

В приведенной выше программе мы можем использовать следующие сценарии:

Если файл c: lists.txt не существует, в выводе консоли ничего не будет отображаться.

Если переменная userprofile не существует, в выводе консоли ничего не будет отображаться.

Если оба вышеуказанных условия выполнены, в командной строке будет отображена строка «Успешное завершение».

Если файл c: lists.txt не существует, в выводе консоли ничего не будет отображаться.

Если переменная userprofile не существует, в выводе консоли ничего не будет отображаться.

Если оба вышеуказанных условия выполнены, в командной строке будет отображена строка «Успешное завершение».

Loops

В главе, посвященной принятию решений, мы увидели утверждения, которые последовательно выполнялись одно за другим. Кроме того, реализации также могут быть выполнены в пакетном скрипте, чтобы изменить поток управления в логике программы. Затем они классифицируются в поток контрольных операторов.

S.No Петли и описание
1 При реализации заявления

В Batch Script нет прямого оператора while, но мы можем очень легко реализовать этот цикл, используя оператор if и метки.

Конструкция «FOR» предлагает возможности зацикливания для пакетных файлов. Ниже приведена общая конструкция оператора for для работы со списком значений.

Оператор for также может перемещаться по диапазону значений. Ниже приводится общая форма заявления.

Ниже приводится классический оператор for, который доступен в большинстве языков программирования.

В Batch Script нет прямого оператора while, но мы можем очень легко реализовать этот цикл, используя оператор if и метки.

Конструкция «FOR» предлагает возможности зацикливания для пакетных файлов. Ниже приведена общая конструкция оператора for для работы со списком значений.

Оператор for также может перемещаться по диапазону значений. Ниже приводится общая форма заявления.

Ниже приводится классический оператор for, который доступен в большинстве языков программирования.

Цикл по аргументам командной строки

Оператор ‘for’ также можно использовать для проверки аргументов командной строки. В следующем примере показано, как можно использовать оператор for для циклического перебора аргументов командной строки.

пример

Выход

Давайте предположим, что приведенный выше код хранится в файле с именем Test.bat. Приведенная выше команда выдаст следующий вывод, если командный файл передает аргументы командной строки 1,2 и 3 как Test.bat 1 2 3.

Оператор break используется для изменения потока управления внутри циклов в любом языке программирования. Оператор break обычно используется в конструкциях цикла и используется для немедленного завершения самого внутреннего замкнутого цикла.

Источник

Читайте также:  Dig l21 huawei прошивка

Adblock
detector


By default when a command line execution is completed it should either return zero when execution succeeds or non-zero when execution fails. When a batch script returns a non-zero value after the execution fails, the non-zero value will indicate what is the error number. We will then use the error number to determine what the error is about and resolve it accordingly.

Following are the common exit code and their description.

Error Code Description
0 Program successfully completed.
1 Incorrect function. Indicates that Action has attempted to execute non-recognized command in Windows command prompt cmd.exe.
2 The system cannot find the file specified. Indicates that the file cannot be found in specified location.
3 The system cannot find the path specified. Indicates that the specified path cannot be found.
5 Access is denied. Indicates that user has no access right to specified resource.

9009

0x2331

Program is not recognized as an internal or external command, operable program or batch file. Indicates that command, application name or path has been misspelled when configuring the Action.

221225495

0xC0000017

-1073741801

Not enough virtual memory is available.

It indicates that Windows has run out of memory.

3221225786

0xC000013A

-1073741510

The application terminated as a result of a CTRL+C. Indicates that the application has been terminated either by the user’s keyboard input CTRL+C or CTRL+Break or closing command prompt window.

3221225794

0xC0000142

-1073741502

The application failed to initialize properly. Indicates that the application has been launched on a Desktop to which the current user has no access rights. Another possible cause is that either gdi32.dll or user32.dll has failed to initialize.

Error Level

The environmental variable %ERRORLEVEL% contains the return code of the last executed program or script.

By default, the way to check for the ERRORLEVEL is via the following code.

Syntax

IF %ERRORLEVEL% NEQ 0 ( 
   DO_Something 
)

It is common to use the command EXIT /B %ERRORLEVEL% at the end of the batch file to return the error codes from the batch file.

EXIT /B at the end of the batch file will stop execution of a batch file.

Use EXIT /B < exitcodes > at the end of the batch file to return custom return codes.

Environment variable %ERRORLEVEL% contains the latest errorlevel in the batch file, which is the latest error codes from the last command executed. In the batch file, it is always a good practice to use environment variables instead of constant values, since the same variable get expanded to different values on different computers.

Let’s look at a quick example on how to check for error codes from a batch file.

Example

Let’s assume we have a batch file called Find.cmd which has the following code. In the code, we have clearly mentioned that we if don’t find the file called lists.txt then we should set the errorlevel to 7. Similarly, if we see that the variable userprofile is not defined then we should set the errorlevel code to 9.

if not exist c:lists.txt exit 7 
if not defined userprofile exit 9 
exit 0

Let’s assume we have another file called App.cmd that calls Find.cmd first. Now, if the Find.cmd returns an error wherein it sets the errorlevel to greater than 0 then it would exit the program. In the following batch file, after calling the Find.cnd find, it actually checks to see if the errorlevel is greater than 0.

Call Find.cmd

if errorlevel gtr 0 exit 
echo “Successful completion”

Output

In the above program, we can have the following scenarios as the output −

  • If the file c:lists.txt does not exist, then nothing will be displayed in the console output.

  • If the variable userprofile does not exist, then nothing will be displayed in the console output.

  • If both of the above condition passes then the string “Successful completion” will be displayed in the command prompt.

Loops

In the decision making chapter, we have seen statements which have been executed one after the other in a sequential manner. Additionally, implementations can also be done in Batch Script to alter the flow of control in a program’s logic. They are then classified into flow of control statements.

S.No Loops & Description
1 While Statement Implementation

There is no direct while statement available in Batch Script but we can do an implementation of this loop very easily by using the if statement and labels.

2 For Statement — List Implementations

The «FOR» construct offers looping capabilities for batch files. Following is the common construct of the ‘for’ statement for working with a list of values.

3 Looping through Ranges

The ‘for’ statement also has the ability to move through a range of values. Following is the general form of the statement.

4 Classic for Loop Implementation

Following is the classic ‘for’ statement which is available in most programming languages.

Looping through Command Line Arguments

The ‘for’ statement can also be used for checking command line arguments. The following example shows how the ‘for’ statement can be used to loop through the command line arguments.

Example

@ECHO OFF 
:Loop 

IF "%1"=="" GOTO completed 
FOR %%F IN (%1) DO echo %%F 
SHIFT 
GOTO Loop 
:completed

Output

Let’s assume that our above code is stored in a file called Test.bat. The above command will produce the following output if the batch file passes the command line arguments of 1,2 and 3 as Test.bat 1 2 3.

1 
2 
3
S.No Loops & Description
1 Break Statement Implementation

The break statement is used to alter the flow of control inside loops within any programming language. The break statement is normally used in looping constructs and is used to cause immediate termination of the innermost enclosing loop.

Topic: How to return success/failure from a batch file?  (Read 195855 times)

0 Members and 1 Guest are viewing this topic.

grevesz

Hello,

I am new to the DOS world. Could someone please help with these questions:

How do I return 0 for success ate the end of an MSDOS batch file?
Similarly, how do I return 1 (or other values) representing erroneous execution?

Thanks in advance!

Gabor


Logged


diablo416

heres an example

@echo off
setlocal enabledelayedexpansion
ping 127.0.0.1
if «%errorlevel%»==»0» cls &Echo Success.
if «%errorlevel%»==»1» cls &Echo Fail
endlocal


Logged


grevesz

Thanks, but that’s not exactly what I had in mind. Let me try to explain it in a different way:
a.bat calls b.bat and when b.bat completes, a.bat continues with steps depending on whether b.bat succeeded or failed.

a.bat:

rem some code here
call b.bat
if "%errorlevel%=="0" goto success
:failure
rem do something
goto end
:success
rem do something else
:end

What would b.bat look like for a.bat to work?

Thanks again!

Gabor


Logged


fireballs

If one of b.bat’s commands fails because of an error then it will set errorlevel to 1 and exit the batch program, returning to a.bat.

What is wrong with the code you provided below?

FB


Logged

Next time google it.


Sidewinder

If one of b.bat’s commands fails because of an error then it will set errorlevel to 1 and exit the batch program, returning to a.bat.

Not quite. Not all MS commands fail with errorlevel 1. XCOPY, for instance can fail with errorlevels 1 to 5. This type of compare («%errorlevel%==»0») becomes dubious at best.

B.bat can use the exit statement to pass a return code (errorlevel) back to a.bat.

Quits the CMD.EXE program (command interpreter) or the current batch
script.

EXIT [/B] [exitCode]

  /B          specifies to exit the current batch script instead of
              CMD.EXE.  If executed from outside a batch script, it
              will quit CMD.EXE

  exitCode    specifies a numeric number.  if /B is specified, sets
              ERRORLEVEL that number.  If quitting CMD.EXE, sets the process
              exit code with that number.

 

8)


Logged

The true sign of intelligence is not knowledge but imagination.

— Albert Einstein


fireballs

If one of b.bat’s commands fails because of an error then it will set errorlevel to 1 and exit the batch program, returning to a.bat.

Not quite. Not all MS commands fail with errorlevel 1. XCOPY, for instance can fail with errorlevels 1 to 5. This type of compare («%errorlevel%==»0») becomes dubious at best.

B.bat can use the exit statement to pass a return code (errorlevel) back to a.bat.

Quits the CMD.EXE program (command interpreter) or the current batch
script.

EXIT [/B] [exitCode]

  /B          specifies to exit the current batch script instead of
              CMD.EXE.  If executed from outside a batch script, it
              will quit CMD.EXE

  exitCode    specifies a numeric number.  if /B is specified, sets
              ERRORLEVEL that number.  If quitting CMD.EXE, sets the process
              exit code with that number.

 8)

yes there are instances where the errorlevel won’t be 1 choice returns 254 if there’s an error. exit requires that you use the same if error gtr 0 but with exit as the command

FB


Logged

Next time google it.


Sidewinder

exit requires that you use the same if error gtr 0 but with exit as the command

Don’t really understand this. I was thinking more along the line where b.bat would abort early based on some condition:

b.bat

if not exist c:file.ext exit 7
if not defined userprofile exit 9
exit 0

a.bat could the query the errorlevel and proceed accordingly, which is what I interpreted the OP requested.

 8)


Logged

The true sign of intelligence is not knowledge but imagination.

— Albert Einstein


fireballs

exit requires that you use the same if error gtr 0 but with exit as the command

Don’t really understand this. I was thinking more along the line where b.bat would abort early based on some condition:

b.bat

if not exist c:file.ext exit 7
if not defined userprofile exit 9
exit 0

a.bat could the query the errorlevel and proceed accordingly, which is what I interpreted the OP requested.

 8)

sorry i’ve beed drinking so my post contained several spelling mistakes, what i meant is that you’d still have to specify under what conditions to exit with a specific exit condition using the if command.

it requires a finite amount of things that could be an error. if you use

if errorlevel gtr 0 exit /b [1] anything over errorleve==1 would exit with exit code 1

FB


Logged

Next time google it.


devcom

you can use:

&& if success
|| if fail

example:

set /a var=1/0 && echo A
set /a var=1/0 || echo A


Logged


grevesz

If one of b.bat’s commands fails because of an error then it will set errorlevel to 1 and exit the batch program, returning to a.bat.

Not quite. Not all MS commands fail with errorlevel 1. XCOPY, for instance can fail with errorlevels 1 to 5. This type of compare («%errorlevel%==»0») becomes dubious at best.

B.bat can use the exit statement to pass a return code (errorlevel) back to a.bat.

Quits the CMD.EXE program (command interpreter) or the current batch
script.

EXIT [/B] [exitCode]

  /B          specifies to exit the current batch script instead of
              CMD.EXE.  If executed from outside a batch script, it
              will quit CMD.EXE

  exitCode    specifies a numeric number.  if /B is specified, sets
              ERRORLEVEL that number.  If quitting CMD.EXE, sets the process
              exit code with that number.

 8)

That’s exactly what I was looking for!
Thanks a lot!
Works like a charm!

Gabor


Logged


billrich

C:>A.bat
 «Hello World»
 «Call  B.bat»
«We are in B.bat.»
«Return exit code from B.bat»
«errorlevel=77»
 77
Press any key to continue . . .
C:>type A.bat
@ECHO OFF

echo  «Hello World»

echo  «Call  B.bat»

Call B.bat

echo «Return exit code from B.bat»

echo «errorlevel=%errorlevel%»
echo  %errorlevel%
pause

C:>type B.bat
REM  return exit code to Batch A.bat
@ECHO OFF

echo «We are in B.bat.»

exit /B  77

C:>


Logged


BC_Programmer

 

::)

a little late to the party, methinks…

Reply #9 on: September 10, 2008, 09:45:23 AM


Logged

I was trying to dereference Null Pointers before it was cool.


alfps

How do I return 0 for success ate the end of an MSDOS batch file?
Similarly, how do I return 1 (or other values) representing erroneous execution?

The most direct way is via

exit /b

value,

However, in Windows 8.1 at least, that doesn’t support

&&

and

||

in the invoking command.

To make those operators work, exit via the end of the batch file, where you place a

cmd /c exit

value, e.g.,

@echo off
setlocal
set E_FAIL=2147500037
set exit_code=%E_FAIL%

set /p a=Pretend to succeed (y/n)?
if "%a%"=="y" goto succeed

:fail
set exit_code=%E_FAIL% & goto finish

:succeed
set exit_code=0 & goto finish

:finish
cmd /c exit %exit_code%


For example, if that file is called

cmd_status.bat

, then you can test it with

cmd_status && echo OK || echo Bah


Logged


patio

The Topic is 6 Years old…
Don’t think he’ll return.


Logged

» Anyone who goes to a psychiatrist should have his head examined. «


alabamasuch

heres an example

@echo off
setlocal enabledelayedexpansion
ping 127.0.0.1
if «%errorlevel%»==»0» cls &Echo Success.
if «%errorlevel%»==»1» cls &Echo Fail
endlocal


Logged


Error Handling in Batch Script

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:BATCHYourfile.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.

Return codes are the codes returned by programs when they are executed. If the command line is successful, it should return zero; if it is not successful, it should return non-zero. If the test fails, a non-zero value indicates the error number, and the user can attempt to resolve it by navigating to the error message.

The test may also return an exit code. A program’s or utility’s exit code usually appears when it finishes or terminates.

The list below includes some of the non-zero exit codes (with their respective errors) that programs may return

Error Code Description
0 Successful completion of the program.
This error indicates that the Windows command prompt has attempted to execute an unrecognized action
2 An error indicating that the file could not be found in the specified location
3 An error message indicated that the specified path could not be found.
5 An indication that the user is not authorized to access the resource
90090×2331 This error occurs when you misspell the command, application name, or path when configuring an Action.
2212254950xC0000017-1073741801 The error message tells you that Windows has run out of memory.
32212257860xC000013A-1073741510  This indicates that the user terminated the application
32212257940xC0000142-1073741502  The message indicating that the application was launched on a desktop to which the current user doesn’t have access

Batch file error level:

%ERRORLEVEL% is an environment variable that contains the last error level or return code in the batch file – that is, the last error code of the last command executed. Error levels may be checked by using the %ERRORLEVEL% variable as follows:

IF %ERRORLEVEL% NEQ 0 (
  DO_Something
)

A common method of returning error codes from batch files is to use the command EXIT /B %ERRORLEVEL%.

For custom return codes, use the EXIT /B <exitcodes> command.

Example:

 In the below example, if the condition is met, the script will terminate with the exit code 0. If the condition isn’t met, then the exit code will be 1.

if [[ "$(whoami)" != root ]]; then
   echo "Not root user."
   exit 1
fi
echo "root user"
exit 0

Output:

Output

Loops:

There have been statements enacted sequentially in the decision-making chapter. Alternatively, Batch Script can also be used to alter the flow of control in a program’s logic. These statements are then organized into flow control statements.

Serial No Loops Description
1 While Statement Implementation There is no direct while statement in Batch Script, although labels and an if statement can be used to implement this loop.
2 For Statement – List Implementations Batch files can loop using the “FOR” construct. In order to work with a list of values, the ‘for’ statement requires the following construct.
3 Looping through Ranges ‘For’ statements can also move through ranges of values. A general version is presented below.
4 Classic for Loop Implementation It has the classic ‘for’ statement found in many programming languages.
5 Break Statement Implementation Within any programming language, the break statement is used to alter the flow of control inside a loop. As part of looping constructs, the break statement causes the innermost enclosing loop to terminate immediately

Looping through Command Line Arguments

For checking command-line arguments, you can use the for statement. Here is an example of how to loop through the arguments of a command line using the ‘for’ statement.

for ((c=1; c<=7; c++))
do  
  echo "Welcome $c times"
done

Output:

Output

Break Statement Implementation

The break statement is used to alter the flow of control inside loops within any programming language. The break statement is normally used in looping constructs and is used to cause immediate termination of the innermost enclosing loop.

Источник

/* steve jansen */

// another day in paradise hacking code and more

Windows Batch Scripting: Return Codes

Today we’ll cover return codes as the right way to communicate the outcome of your script’s execution to the world. Sadly, even skilled Windows programmers overlook the importance of return codes.

Return Code Conventions

By convention, command line execution should return zero when execution succeeds and non-zero when execution fails. Warning messages typically don’t effect the return code. What matters is did the script work or not?

Checking Return Codes In Your Script Commands

The environmental variable %ERRORLEVEL% contains the return code of the last executed program or script. A very helpful feature is the built-in DOS commands like ECHO , IF , and SET will preserve the existing value of %ERRORLEVEL% .

The conventional technique to check for a non-zero return code using the NEQ (Not-Equal-To) operator of the IF command:

Another common technique is:

The ERRORLEVEL 1 statement is true when the return code is any number equal to or greater than 1. However, I don’t use this technique because programs can return negative numbers as well as positive numbers. Most programs rarely document every possible return code, so I’d rather explicity check for non-zero with the NEQ 0 style than assuming return codes will be 1 or greater on error.

You may also want to check for specific error codes. For example, you can test that an executable program or script is in your PATH by simply calling the program and checking for return code 9009.

It’s hard to know this stuff upfront – I generally just use trial and error to figure out the best way to check the return code of the program or script I’m calling. Remember, this is duct tape programming. It isn’t always pretty, but, it gets the job done.

Conditional Execution Using the Return Code

There’s a super cool shorthand you can use to execute a second command based on the success or failure of a command. The first program/script must conform to the convention of returning 0 on success and non-0 on failure for this to work.

To execute a follow-on command after sucess, we use the && operator:

To execute a follow-on command after failure, we use the || operator:

I use this technique heavily to halt a script when any error is encountered. By default, the command processor will continue executing when an error is raised. You have to code for halting on error.

A very simple way to halt on error is to use the EXIT command with the /B switch (to exit the current batch script context, and not the command prompt process). We also pass a specific non-zero return code from the failed command to inform the caller of our script about the failure.

A simliar technique uses the implicit GOTO label called :EOF (End-Of-File). Jumping to EOF in this way will exit your current script with the return code of 1.

Tips and Tricks for Return Codes

I recommend sticking to zero for success and return codes that are positive values for DOS batch files. The positive values are a good idea because other callers may use the IF ERRORLEVEL 1 syntax to check your script.

I also recommend documenting your possible return codes with easy to read SET statements at the top of your script file, like this:

Note that I break my own convention here and use uppercase variable names – I do this to denote that the variable is constant and should not be modified elsewhere. Too bad DOS doesn’t support constant values like Unix/Linux shells.

Some Final Polish

One small piece of polish I like is using return codes that are a power of 2.

This gives me the flexibility to bitwise OR multiple error numbers together if I want to record numerous problems in one error code. This is rare for scripts intended for interactive use, but, it can be super helpful when writing scripts you support but you don’t have access to the target systems.

If both SomeCommand.exe and OtherCommand.exe fail, the return code will be the bitwise combination of 0x1 and 0x2, or decimal 3. This return code tells me that both errors were raised. Even better, I can repeatedly call the bitwise OR with the same error code and still interpret which errors were raised.

Posted by Steve Jansen Mar 1 st , 2013 batch, scripting, shell, windows

Comments

Hi, I’m Steve. I’m a software developer loving life in Charlotte, NC, an (ISC) 2 CSSLP and an avid fan of Crossfit.

And, no, I’m not Steve Jansen the British jazz drummer, though that does sound like a sweet career.

Guides

Recent Posts

Social Stuff

  • @steve-jansen on GitHub
  • @steve-jansen on StackOverflow
  • @steve-jansen ProTips on Coderwall
  • @steve-jansen on Microsft Connect
  • @steve-jansen on ASP.NET User Voice
  • Subscribe via RSS

Copyright © 2015 — Steve Jansen — Powered by Octopress

Источник

Error Handling in Batch Script

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:

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:

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:

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.

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:

Then we will get an output like this:

Remember, all commands we discussed here are only for the Windows Command Prompt or CMD environment.

Aminul Is an Expert Technical Writer and Full-Stack Developer. He has hands-on working experience on numerous Developer Platforms and SAAS startups. He is highly skilled in numerous Programming languages and Frameworks. He can write professional technical articles like Reviews, Programming, Documentation, SOP, User manual, Whitepaper, etc.

Источник

Adblock
detector

Понравилась статья? Поделить с друзьями:
  • Exiled kingdoms ошибка правосудия
  • Exiled kingdom ошибка правосудия
  • Exiftoolgui error exiftool not found
  • Exif read data error
  • Exhaust system warning на daf ошибка