- Команда EXIT – завершить работу командного процессора или текущего командного файла.
- Команда EXIT: выход из командной строки Windows или командного файла
- exit exit
- Синтаксис Syntax
- Параметры Parameters
- Примеры Examples
- How to Open Command Prompt
- Open Command Prompt to Execute Commands in Windows 10, 8, 7, Vista, & XP
- Open Command Prompt in Windows 10
- Open Command Prompt Through the Start Menu
- Open Command Prompt Using Power User Menu
- Open Command Prompt in Windows 8 or 8.1
- Open Command Prompt in Windows 7, Vista, or XP
- Other Ways to Open Command Prompt
- Elevated Command Prompts and Old Windows Versions
- How do I get the application exit code from a Windows command line?
- 7 Answers 7
- Example
Команда 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: выход из командной строки 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 не только в том, что она помогает закрывать окно командной строки без помощи мыши.
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 to Open Command Prompt
Open Command Prompt to Execute Commands in Windows 10, 8, 7, Vista, & XP
Some popular Command Prompt commands you might have heard of include ping, netstat, tracert, shutdown, and attrib, but there are many more. We have a complete list here.
While Command Prompt probably isn’t a tool most of you will use on a regular basis, it can really come in handy now and then, maybe to troubleshoot a specific Windows problem or to automate some kind of task.
How you open Command Prompt differs between Windows versions, so you’ll find steps below for Windows 10, Windows 8 or Windows 8.1, and Windows 7, Windows Vista, and Windows XP. See What Version of Windows Do I Have? if you’re not sure.
Open Command Prompt in Windows 10
Select the Start button.
Type cmd.
Select Command Prompt from the list.
Open Command Prompt Through the Start Menu
Another way to open Command Prompt in Windows 10 is to look in its Start menu folder:
Select the Start button.
Select the Windows System folder from the list.
Choose Command Prompt from the folder group.
Open Command Prompt Using Power User Menu
One more method in Windows 10 is through the Power User Menu. If you’re using a keyboard or mouse, choose Command Prompt from the menu that appears after pressing Win+X or right-clicking the Start button.
You might see Windows PowerShell options in the Power User Menu instead of Command Prompt. In more recent versions of Windows 10, Command Prompt has been replaced by PowerShell, but you can still access it from the Power User Menu by editing the taskbar settings.
Open Command Prompt in Windows 8 or 8.1
Select the Start button and then swipe up to show the Apps screen. You can accomplish the same thing with a mouse by selecting the down arrow icon at the bottom of the screen.
Prior to the Windows 8.1 update, the Apps screen can be accessed from the Start screen by swiping up from the bottom of the screen, or right-clicking anywhere, and then choosing All apps.
If you’re using a keyboard or mouse, a really quick way to open a Command Prompt window in Windows 8 is through the Power User Menu—just hold the WIN and X keys down together, or right-click the Start button, and choose Command Prompt.
Swipe or scroll to the right on the Apps screen to locate the Windows System section heading.
Select Command Prompt. You can now execute whatever command you needed to run.
See our List of Windows 8 Command Prompt Commands for a complete list of the commands available through Command Prompt in Windows 8, including short descriptions and links to more in-depth information if we have it.
Open Command Prompt in Windows 7, Vista, or XP
Open the Start menu from the bottom-left corner of the screen.
In Windows 7 and Windows Vista, it’s a bit faster to enter command in the search box at the bottom of the Start menu and then choose Command Prompt when it appears in the results.
Go to All Programs > Accessories.
Choose Command Prompt from the list of programs.
Here’s our List of Windows 7 Commands and List of Windows XP Commands if you need a command reference for any of those versions of Windows.
Other Ways to Open Command Prompt
Command Prompt in Windows XP through Windows 10 can also be opened with a command. This is especially helpful if you like using the Run dialog box or if Windows Explorer has crashed and the Start menu is inaccessible (and thus the directions above don’t work).
To do this, enter cmd into the command-line interface. This can be in the Run dialog box (WIN+R) or Task Manager’s File > Run new task menu.
Elevated Command Prompts and Old Windows Versions
In versions of Windows released before Windows XP, like Windows 98 and Windows 95, Command Prompt doesn’t exist. However, the older and very similar MS-DOS Prompt does. This program is located in the Start menu and can be opened with the command run command.
Some commands, like the sfc command that’s used to repair Windows files, require that Command Prompt be opened as an administrator before they can be executed. You’ll know if this is the case if you get a message like one of these after trying to execute the command:
- check that you have administrative rights
- . command can only be executed from an elevated command prompt
- you must be an administrator
See How to Open an Elevated Command Prompt for help starting Command Prompt as an administrator, a process that’s a bit more complicated than what’s outlined above.
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 .