Как завершить выполнение пакетного файла
Перейти к содержимому

Как завершить выполнение пакетного файла

  • автор:

EXIT

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

EXIT

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.

GOTO:EOF is available in Windows NT 4 and later versions’ CMD.EXE only.

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 Leave command prompt open Close console window Leave subroutine and return to calling code
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

page last modified: 2016-09-19; loaded in 0.0058 seconds

How to end task in batch?

How to end/stop a task/programm in batch-files quickly ? If it’s possible to stop all programms with one command please say it to me. I tried taskkill firefox But it doesnt work Thank you for answers ; )

asked Aug 26, 2017 at 12:07
user8470476 user8470476
1 1 1 silver badge 3 3 bronze badges

2 Answers 2

TASKKILL /IM notepad.exe 

You can replace the taskname notepad.exe with your process.

You can check running process from Task manager » Process

you can find the Firefox process name there, if it is running.

answered Aug 26, 2017 at 17:38
409 5 5 silver badges 13 13 bronze badges
Thank you for you answer
Aug 27, 2017 at 19:30

Here is a batch file to kill a process or many processes separated by a space :

@echo off Title Process Killer by Hackoo 2017 Mode 80,5 & color 0B Set "TmpFile=%Temp%\TmpFile.txt" Set "Result=%Temp%\KillResult.txt" If Exist "%TmpFile%" Del "%TmpFile%" If Exist "%Resultat%" Del "%Resultat%" echo( echo Enter the process name or processes names separated by a space echo( set /p "process=What process(es) do you want to kill ? > " cls & color 0C Title Killing "%process%" . echo( echo %date% *** %time% >"%TmpFile%" For %%a in (%process%) Do Call :KillMyProcess %%a Cmd /U /C Type "%TmpFile%" >"%Result%" Timeout /T 2 /nobreak>nul Start "" "%Result%" ::********************************************************************************************* :KillMyProcess Set "Process=%~1" echo Killing "%process%" . echo "%Process%" | find /I ".exe" >nul 2>&1 && ( Taskkill /IM "%Process%" /F >>"%TmpFile%" 2>&1 ) || ( Taskkill /IM "%~n1.exe" /F >>"%TmpFile%" 2>&1 ) echo *****************************************************************************>>"%TmpFile%" exit /b ::********************************************************************************************** 

Команда 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 и оцените полученный результат.

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:

tncserver.exe C:\Work -p4 -b57600 -r -cFE -tTNC426B exit 

1,044 1 1 gold badge 14 14 silver badges 30 30 bronze badges
asked Jan 31, 2013 at 12:47
Blitzcrank Blitzcrank
937 2 2 gold badges 10 10 silver badges 19 19 bronze badges

11 Answers 11

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

start "" tncserver.exe C:\Work -p4 -b57600 -r -cFE -tTNC426B 

answered Jan 31, 2013 at 12:53
30.8k 35 35 gold badges 124 124 silver badges 152 152 bronze badges
hohoho, should be like this: start tncserver.exe C:\Work -p4 -b57600 -r -cFE -tTNC426B
Jan 31, 2013 at 13:12

The «» is used to stop a problem with start , if the program you are running has spaces it will interpret the first string as the title for the app. The «» gives it a blank title so the rest will work as expected.

Jan 31, 2013 at 13:14

Just wanted to make an addition here, I was running a minecraft server which upon the /restart command would launch the bat script, the old command prompt wouldn’t close however, instead it would go back to the command line. using «exit» at the end of the bat script fixed that for me

Oct 21, 2016 at 11:34

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

 tncserver.exe C:\Work -p4 -b57600 -r -cFE -tTNC426B exit 0 

answered Jan 31, 2013 at 13:01
Gaurav Kolarkar_InfoCepts Gaurav Kolarkar_InfoCepts
1,507 9 9 silver badges 11 11 bronze badges

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 start iexplore "http://your/url.html" 

cmd /c means executing a command and then exit.

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

anycmd /? 

answered Oct 30, 2017 at 20:20
Jenna Leaf Jenna Leaf
2,325 22 22 silver badges 29 29 bronze badges

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

start C:/Anaconda3/Library/bin/pyrcc4.exe -py3 /Resourses.qrc -/Resourses_rc.py exit 

14.6k 11 11 gold badges 60 60 silver badges 80 80 bronze badges
answered Jan 10, 2016 at 19:45
user5770752 user5770752
121 1 1 silver badge 2 2 bronze badges

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

2,053 4 4 gold badges 10 10 silver badges 17 17 bronze badges
answered Feb 3, 2016 at 7:27
user1448914 user1448914
99 2 2 silver badges 9 9 bronze badges

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

start "" "C:\Program Files (x86)\Xming\Xming.exe" -screen 0 -clipboard -multiwindow 

answered Sep 16, 2014 at 14:42
398 2 2 silver badges 8 8 bronze badges

On windows11 I’m concatenating commands like this

cmd /c dotnet lsb && npm run build:dev && exit 0

in this example it runs in a single shell the two commands and then closes it.

answered Apr 16, 2023 at 0:45
Not Important Not Important
804 7 7 silver badges 24 24 bronze badges

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:

call [BEA_HOME]\user_projects\domains\test_domain\startWebLogic.cmd 

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

answered Nov 30, 2019 at 20:50
user2590805 user2590805
410 4 4 silver badges 6 6 bronze badges

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

echo | set /p=Your Text 
Your Text 

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

echo | set /p=Text| clip 

answered Jun 7, 2021 at 22:52
Luka Urushadze Luka Urushadze
25 1 1 silver badge 7 7 bronze badges

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

I believe for complex scripts that output and have pauses in them such as «timeout /t 4 /nobreak», his idea is best. Simply force-killing cmd.exe can/will mess up systems that are running background processes inside of cmd.exe containers, while that command will only kill visible windows with cmd.exe in the title.

For reference it was:

REM EXECUTE TASK KILL TO CLOSE CMD PROGRAM.- wmic Path win32_process Where "Caption Like 'cmd%.exe'" Call Terminate 

Put it in the last code line of your batch file program.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *