Windows command file exit code

exit exit

Область применения: Windows Server (половина ежегодного канала), Windows Server 2019, Windows Server 2016, Windows Server 2012 R2, Windows Server 2012 Applies to: Windows Server (Semi-Annual Channel), Windows Server 2019, Windows Server 2016, Windows Server 2012 R2, Windows Server 2012

Выход из интерпретатора команд или текущего пакетного скрипта. Exits the command interpreter or the current batch script.

Синтаксис Syntax

Параметры Parameters

Параметр Parameter Описание Description
/b /b Выход из текущего пакетного скрипта вместо выхода из Cmd.exe. Exits the current batch script instead of exiting Cmd.exe. Если выполняется из-за пределов пакетного скрипта, выполняет выход из Cmd.exe. If executed from outside a batch script, exits Cmd.exe.
Указывает числовое число. Specifies a numeric number. Если указан параметр /b , переменной среды ERRORLEVEL присваивается это число. If /b is specified, the ERRORLEVEL environment variable is set to that number. Если интерпретатор команд закрывается, код завершения процесса устанавливается в это число. If you are quitting the command interpreter, the process exit code is set to that number.
/? /? Отображение справки в командной строке. Displays help at the command prompt.

Примеры Examples

Чтобы закрыть интерпретатор команд, введите: To close the command interpreter, type:

Команда EXIT: выход из командной строки Windows или командного файла

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

У команды exit есть и второе предназначение — выход из текущего командного файла. Допустим, что в текущем окне командного интерпретатора у вас исполняется какой-то BAT-файл или CMD-файл. Если нужно выйти из него, не закрывая окно командной строки, это также можно сделать командой exit . Синтаксис и примеры ниже.

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

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

Команда выше просто закроет окно командной строки.

Нередки ситуации, когда один командный файл вызывает другой командный файл. Предположим, что файл primer1.bat вызывает файл primer2.bat. Используя команду exit , мы вызовем закрытие файла primer2.bat, а также primer1.bat, после чего закроется и окно командной строки.

Чтобы этого не произошло, используем /b . Допустим, что файл primer1.bat вызывает primer2.bat и выводит на экран значение ERRORLEVEL, которое взято при выходе из primer2.bat:

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

Это приведёт к выводу следующего сообщения:

Как видите, польза команды exit не только в том, что она помогает закрывать окно командной строки без помощи мыши.

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.

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)

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 .

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.

Читайте также:  Yandex браузер v15 mac os
Оцените статью