- Команда EXIT – завершить работу командного процессора или текущего командного файла.
- exit exit
- Синтаксис Syntax
- Параметры Parameters
- Примеры Examples
- How do I get the application exit code from a Windows command line?
- 7 Answers 7
- Example
- Windows cmd process exit code
- Errorlevel
- Ctrl-C
- Как получить код завершения приложения из командной строки Windows?
- пример
Команда 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 и оцените полученный результат.
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:
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 .
Windows cmd process exit code
Close the current batch script, exit the current subroutine or close the CMD.EXE session, optionally setting an errorlevel.
To close an interactive command prompt, the keyboard shortcut ALT + F4 is an alternative to typing EXIT.
Errorlevel
EXIT /b has the option to set a specific errorlevel, EXIT /b 0 for sucess, EXIT /b 1 (or greater) for an error.
The exit code can be an integer of up to 10 digits in length (positive or negative).
EXIT without an ExitCode acts the same as goto:eof and will not alter the ERRORLEVEL
n.b. You should never attempt to directly write to the %ERRORLEVEL% variable, ( SET ERRORLEVEL n ) instead use EXIT /b n as a safe way to set the internal ERRORLEVEL pseudo variable to n .
Ctrl-C
An errorlevel of -1073741510 will be interpreted by CMD.exe as a Ctrl-C Key sequence to cancel the current operation, not the entire script which EXIT will do.
To use this in a batch file, launch a new CMD session and immediately exit it, passing this errorlevel. The script will then act as though Ctrl-C had been pressed. Source and examples on DosTips.com.
::Ctrl-C
cmd /c exit -1073741510
When EXIT /b used with FOR /L, the execution of the commands in the loop is stopped, but the loop itself continues until the end count is reached. This will cause slow performance if the loop is (pointlessly) counting up to a large number.
In the case of an infinite loop, this EXIT /b behaviour will cause the script to hang until manually terminated with Ctrl + C
Exiting nested FOR loops, EXIT /b can be used to exit a FOR loop that is nested within another FOR loop.
This will only work if the inner FOR loop is contained in a separate subroutine, so that EXIT /b (or goto:eof) will terminate the subroutine.
Exit if a required file is missing:
@Echo Off
If not exist MyimportantFile.txt Exit /b
Echo If we get this far the file was found
@Echo Off
Call :setError
Echo %errorlevel%
Goto :eof
:setError
Exit /B 5
Use EXIT /b to exit a nested FOR loop (so skipping the values X,Y and Z), but still continue back to the main outer loop:
EXIT is an internal command.
If Command Extensions are disabled, the EXIT command will still work but may output a spurious ‘cannot find the batch label‘ error.
“Making music is not about a place you go. It’s about a place you get out of. I’m underwater most of the time, and music is like a tube to the surface that I can breathe through. It’s my air hole up to the world. If I didn’t have the music I’d be under water, dead”
VERIFY — Provides an alternative method of raising an error level without exiting.
TSKILL — End a running process.
Powershell: Exit — Exit Powershell or break — Exit a program loop.
Equivalent bash command (Linux): break — Exit from a loop.
Как получить код завершения приложения из командной строки Windows?
Я запускаю программу и хочу посмотреть, каков ее код возврата (так как он возвращает разные коды на основе разных ошибок).
Я знаю, в Баш я могу сделать это, запустив
Что мне делать при использовании cmd.exe в Windows?
Псевдопеременная переменная named errorlevel хранит код выхода:
Также if команда имеет специальный синтаксис:
Смотрите if /? подробности.
пример
Предупреждение: если вы зададите имя переменной среды errorlevel , %errorlevel% будет возвращено это значение, а не код выхода. Используйте ( set errorlevel= ) для очистки переменной среды, предоставляя доступ к истинному значению переменной errorlevel через %errorlevel% переменную среды.
Тестирование ErrorLevel работает для консольных приложений, но, как намекнул dmihailescu , это не сработает, если вы пытаетесь запустить оконное приложение (например, на основе Win32) из командной строки. Оконное приложение будет работать в фоновом режиме, и элемент управления немедленно вернется в командную строку (скорее всего, с ErrorLevel нулем, указывающим, что процесс был успешно создан ). Когда оконное приложение в конечном итоге завершает работу, его состояние выхода теряется.
Однако вместо использования средства запуска C ++ на основе консоли, упомянутого в другом месте, более простой альтернативой является запуск оконного приложения с помощью команды командной строки START /WAIT . Это запустит оконное приложение, дождется его завершения и вернет управление в командную строку со статусом завершения процесса, установленным в ErrorLevel .