Windows bat check exit code

Команда EXIT – завершить работу командного процессора или текущего командного файла.

Команда EXIT используется для завершения пакетных файлов с установкой значения переменной ERRORLEVEL или для завершения командного процессора CMD.EXE ( для выхода из командной строки), если она выполняется вне пакетного файла.

Формат командной строки:

EXIT [/B] [exitCode]

Параметры командной строки:

/B — Предписывает завершить текущий пакетный файл-сценарий вместо завершения CMD.EXE. Если выполняется вне пакетного файла-сценария, то будет завершена программа CMD.EXE

exitCode — Указывает цифровое значение. Если указан ключ /B, определяет номер для ERRORLEVEL. В случае завершения работы CMD.EXE, устанавливает код завершения процесс с данным номером.

Примеры использования команды EXIT

exit — завершить текущий сеанс CMD

Команда EXIT с параметрами используются, как правило, только в командных файлах. Например, для индикации результата выполнения с установкой значения переменной среды ERRORLEVEL

REM перейти к метке, где выполняется выход с ERRORLEVEL=0

REM перейти к метке, где выполняется выход с ERRORLEVEL=1

REM установить ERRORLEVEL равный 0 и завершить работу

REM установить ERRORLEVEL равный 1 и завершить работу

Параметр /B используется в тех случаях, когда выполняется завершение командного файла, но необходимо продолжить работу командного процессора. Например, когда командный файл 1.bat вызывает командной CALL другой командный файл 2.bat , результат выполнения которого, характеризуется значением переменной окружения ERRORLEVEL . Если в вызываемом командном файле использовать команду EXIT без параметра /B, то будет завершена работа вызываемого файла 2.bat, а также вызывающего файла 1 .bat и интерпретатора CMD.EXE, т.е вместо выхода из вызываемого файла будет полностью завершен сеанс командной строки.

Простейший пример, когда командный файл 1.bat вызывает на выполнение другой командный файл с именем 2.bat и выводит на экран значение ERRORLEVEL, установленное при выходе из вызываемого файла:

echo Batch file 2.bat executed with ERRORLEVEL = %ERRORLEVEL%

Файл 2.bat завершается командой EXIT с установкой значения ERRORLEVEL, равного 128:

При выполнении командного файла 1.bat на экран будет выведено сообщение:

Batch file 2.bat executed with ERRORLEVEL = 128

Попробуйте убрать параметр /B в команде EXIT командного файла 2.bat и оцените полученный результат.

ERRORLEVEL это не %ERRORLEVEL%

У командный процессора cmd.exe есть такая вещь — уровень ошибки (error level). Это код выхода (exit code) программы, которую вы запускали последней. Проверить уровень ошибки можно при помощи команды IF ERRORLEVEL .

IF ERRORLEVEL 1 ECHO error level is 1 or more

Проверка IF ERROR LEVEL n срабатывает, если уровень ошибки n или выше. Это, вероятно, потому, что многие программы выражают разную степень ошибки все большими и большими кодах выхода. К примеру, программа diff имеет 3 кода выхода: «0» означает, что файлы одинаковые, «1» — разные, «2» — случилось что-то страшное. Некоторые программы используют код выхода «0» для успеха и все остальное для ошибки.

Вдобавок к этому внутреннему состоянию, вы, если хотите, можете создать переменную окружения с именем ERRORLEVEL , так же, как вы можете создать переменную с именем FRED . Но, как и FRED , эта переменная не повлияет на уровень ошибки.

Читайте также:  Список устройств linux терминал

rem this next command sets the error level to zero
CMD /C EXIT 0
set ERRORLEVEL=1
if ERRORLEVEL 1 echo Does this print?

Сообщение не будет отображено, поскольку переменная ERRORLEVEL не имеет никакого влияния на уровень ошибки. Это просто переменная, имя которой совпадает с концепцией командного процессора.

set BANKBALANCE=$1 000 000,00

«Эй, когда я пытаюсь снять денег, у меня ошибка — „недостаточно денег на счету“».

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

То же поведение и у %CD% : если вы не установили переменную с таким именем, подставляется текущий каталог командного процессора. Но изменить каталог при помощи set CD=C:\Windows нельзя.

Вероятно, есть несколько причин для такого поведения:
— Чтобы можно было вывести уровень ошибки в лог:
ECHO error level is %ERRORLEVEL%>logfile
— Чтобы можно было выполнять другие сравнения с уровнем ошибки — например, чтобы проверять равенство:
IF %ERRORLEVEL% EQU 1 echo Different!

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

How do I get the application exit code from a Windows command line?

I am running a program and want to see what its return code is (since it returns different codes based on different errors).

I know in Bash I can do this by running

What do I do when using cmd.exe on Windows?

7 Answers 7

A pseudo environment variable named errorlevel stores the exit code:

Also, the if command has a special syntax:

See if /? for details.

Example

Warning: If you set an environment variable name errorlevel , %errorlevel% will return that value and not the exit code. Use ( set errorlevel= ) to clear the environment variable, allowing access to the true value of errorlevel via the %errorlevel% environment variable.

Testing ErrorLevel works for console applications, but as hinted at by dmihailescu, this won’t work if you’re trying to run a windowed application (e.g. Win32-based) from a command prompt. A windowed application will run in the background, and control will return immediately to the command prompt (most likely with an ErrorLevel of zero to indicate that the process was created successfully). When a windowed application eventually exits, its exit status is lost.

Instead of using the console-based C++ launcher mentioned elsewhere, though, a simpler alternative is to start a windowed application using the command prompt’s START /WAIT command. This will start the windowed application, wait for it to exit, and then return control to the command prompt with the exit status of the process set in ErrorLevel .

check if command was successful in a batch file

How within a batch file to check if command

was successful or produced an error?

I want to use if/else statements to echo this info out.

5 Answers 5

in some cases. This depends on the last command returning a proper exit code. You won’t be able to tell that there is anything wrong if your program returns normally even if there was an abnormal condition.

Читайте также:  Traceroute in linux with port

Caution with programs like Robocopy, which require a more nuanced approach, as the error level returned from that is a bitmask which contains more than just a boolean information and the actual success code is, AFAIK, 3.

This likely doesn’t work with start , as that starts a new window, but to answer your question:

If the command returns a error level you can check the following ways

By Specific Error Level

By If Any Error

By If No Error

If it does not return a error level but does give output, you can catch it in a variable and determine by the output, example (note the tokens and delims are just examples and would likely fail with any special characters)

By Parsing Full Output

Or you could just look for a single phrase in the output like the word Error

By Checking For String

And you could even mix together (just remember to escape | with ^| if in a for statement)

Batch Script — Return Code

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.

Not enough virtual memory is available.

It indicates that Windows has run out of memory.

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

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

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.

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.

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.

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

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

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.

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.

Читайте также:  Что такое поток windows
Оцените статью