Bat как закрыть окно

от admin

Bat как закрыть окно

Even our favorite batch files will, at some time, need to quit.
Sometimes they need to quit based on a condition that has been or has not been met. And every batch file needs to quit, and will do so, when it reaches the last line of code.

There are several ways to end batch file execution, like reaching the end of the batch file, starting execution of another batch file, or using the EXIT or GOTO:EOF commands.

Each operating system may react in its own way to any of these events.
And often there is a difference between ending batch file execution and closing the batch file’s console (window).

Reaching the end

After the batch file has executed its last line of code it will stop running, unless the last line contained a GOTO command forcing it to re-execute some of its previous code.

When the batch file stops running it will return control to the command processor.
If that command processor was started just for the purpose of executing the batch file, the command processor itself will stop running after completing batch file execution.
This may be the case when a batch file is started by double-clicking a shortcut in Windows or OS/2.

Though the batch file may be terminated, the console (window) the batch file has been running in may be left open, depending on the operating system, the command processor, and how batch file execution was started (from a command prompt or through a shortcut).

Operating System Command Processor Command Prompt Shortcut CALLed subroutine Remarks
MS-DOS 3. 6.22 COMMAND.COM Leave command prompt open N/A N/A
MS-DOS 7.* (Windows 9x) COMMAND.COM Leave command prompt open Leave console window open N/A Make sure no text is displayed in the console window to make it close automatically at the end of the batch file
OS/2 CMD.EXE Leave command prompt open Leave console window open N/A
OS/2 COMMAND.COM Leave command prompt open Leave console window open N/A
Windows NT 4 CMD.EXE Leave command prompt open Close console window Return to CALLing command line
Windows NT 4 COMMAND.COM Leave command prompt open Close console window N/A
Windows 2000/XP/2003 CMD.EXE Leave command prompt open Close console window Return to CALLing command line
Windows 2000/XP/2003 COMMAND.COM Leave command prompt open Close console window N/A

Using EXIT will stop execution of a batch file and return control to the command processor (or, with NT’s /B switch, to the calling batch file) immediately.

Operating System Command Processor Command Prompt Shortcut CALLed subroutine Remarks
MS-DOS 3. 6.22 COMMAND.COM Leave command prompt open N/A N/A
MS-DOS 7.* (Windows 9x) COMMAND.COM Close command prompt Leave console window open N/A Make sure no text is displayed in the console window to make it close automatically at the end of the batch file
OS/2 CMD.EXE Close command prompt Close console window Close command prompt or window
OS/2 COMMAND.COM Close command prompt Close console window N/A
Windows NT 4 CMD.EXE Close command prompt Close console window Close command prompt or window
Windows NT 4 COMMAND.COM Close command prompt Close console window N/A
Windows 2000/XP/2003 CMD.EXE Close command prompt Close console window Close command prompt or window
Windows 2000/XP/2003 COMMAND.COM Close command prompt Close console window N/A

EXIT /B n

Using EXIT /B will stop execution of a batch file or subroutine and return control to the command processor or to the calling batch file or code immediately.

EXIT /B is available in Windows 2000 and later versions’ CMD.EXE only.
If followed by an integer number the code will return an exit code or ERRORLEVEL equal to that number.

Operating System Command Processor Command Prompt Shortcut CALLed subroutine Remarks
MS-DOS 3. 6.22 COMMAND.COM N/A N/A N/A
MS-DOS 7.* (Windows 9x) COMMAND.COM N/A N/A N/A
OS/2 CMD.EXE N/A N/A N/A
OS/2 COMMAND.COM N/A N/A N/A
Windows NT 4 CMD.EXE N/A N/A N/A
Windows NT 4 COMMAND.COM N/A N/A N/A
Windows 2000/XP/2003 CMD.EXE Leave command prompt open Close console window Leave subroutine and return to calling code
Windows 2000/XP/2003 COMMAND.COM N/A N/A N/A

Here is a more detailed explanation by Timothy Dollimore:

The DOS online help ( HELP EXIT ) doesn’t make it clear that the /B parameter exits the current instance of script which is not necessarily the same as exiting the current script.
I.e. if the script is in a CALLed piece of code, the EXIT /B exits the CALL , not the script.

To explain, one can use EXIT /B 0 in a similar fashion to GOTO:EOF to exit (or more accurately, return) from a called section of code inside a script.

GOTO:EOF

In short, GOTO:EOF should have the same result as reaching the end of the batch file.
It marks the end of a subroutine, and returns to the CALLing code.

Команда 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: выход из командной строки Windows или командного файла

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

How to close the command line window after running a batch file?

I’ve got a batch file. After it finished running, i.e. all command lines have been executed, the cmd.exe window stays open. However, I’d like to have it closed right after the batch file finishes its job.

So far I’ve tried using the exit command within the batch file to close the cmd window (I also have a shortcut on the desktop) but it doesn’t seem to work:

Jim McAdams's user avatar

Blitzcrank's user avatar

10 Answers 10

It should close automatically, if it doesn’t it means that it is stuck on the first command.

In your example it should close either automatically (without the exit ) or explicitly with the exit . I think the issue is with the first command you are running not returning properly.

As a work around you can try using

Your code is absolutely fine. It just needs «exit 0» for a cleaner exit.

Gaurav Kolarkar_InfoCepts's user avatar

I added the start and exit which works. Without both it was not working

If you only need to execute only one command all by itself and no wait needed, you should try «cmd /c», this works for me!

cmd /c means executing a command and then exit.

You can learn the functions of your switches by typing in your command prompt

Jenna Leaf's user avatar

%Started Program or Command% | taskkill /F /IM cmd.exe

Example:

notepad.exe | taskkill /F /IM cmd.exe

Unfortunately, if you have other cmd windows open, it kills them as well.

Used this to start Xming, placed the bat file in the Start->Startup directory and now I have xming running on start up.

For closing cmd window, especially after ending weblogic or JBOSS app servers console with Ctrl+C, I’m using ‘ call ‘ command instead of ‘ start ‘ in my batch files. My startWLS.cmd file then looks like:

After Ctrl+C(and ‘Y’ answer) cmd window is automatically closed.

I came across this question while searching the same topic but for Windows So, if anyone wonders how it can be done here is it

I used it to save data on the clipboard so trimming text was necessary It looked like this

Luka Urushadze's user avatar

Max Lorens’s response, currently the least-voted answer, is the only one that works for my particular script.

Форум UPgrade

как закрыть cmd.exe после исполнения батника?

как закрыть cmd.exe после исполнения батника?

Сообщение padsel » 19 окт 2009, 20:28

чтобы при загрузке комп подключался к инету и запускалась опера
написал:

rasphone.exe -d название_соединения
«f:\program files\Opera\opera.exe»
exit

сохранил, как батник и поставил в автозагрузку
всё работает, только cmd.exe не закрывается после выполнения

Re: как закрыть cmd.exe после исполнения батника?

Сообщение older » 20 окт 2009, 12:42

Re: как закрыть cmd.exe после исполнения батника?

Сообщение bzzz » 20 окт 2009, 17:23

ИзображениеИзображение

Re: как закрыть cmd.exe после исполнения батника?

Сообщение Vose » 20 окт 2009, 21:45

Re: как закрыть cmd.exe после исполнения батника?

Сообщение padsel » 21 окт 2009, 04:18

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

да не проблема другими способами запускать, я именно про батник спрашиваю
простой ведь вопрос

__________________________________________________________
На будущее — не надо писать подряд за самим собой. Есть кнопка правка.
У вас ещё одно сообщение будет проходить через премодерацию. Потому, будет видно только после одобрения модера.
Al_lexx

Читать:
Вы действительно хотите отменить все передачи что это

Похожие статьи