How to Exit a Batch File

MD Aminul Islam Feb 02, 2024
  1. Use the EXIT Command to Exit a Batch File
  2. Use GOTO :EOF to Exit a Batch File
  3. Use Both EXIT and GOTO :EOF to Exit a Batch File
How to Exit a Batch File

In this article, we will learn what the use of the EXIT command is and see some examples to make it easier to understand. We also see an alternative way to terminate a script and a combined method.

Use the EXIT Command to Exit a Batch File

The EXIT command is mainly used to terminate the current script.

The general format of using the EXIT command is EXIT /B ExitCode. Here, /B sets the options of specific error levels.

Use EXIT /B 0 to indicate success and EXIT /B 1 to indicate an error. Let’s see an example with its explanation for better understanding.

@echo off
echo The level of error is %errorlevel%
exit /b 1

In this example, we used an EXIT command with the error level of 1. The output of this code is shown below:

The level of error is: 1

Please note that EXIT /B will only exit the currently running script but leave the parent script open.

Use GOTO :EOF to Exit a Batch File

There is an alternative way available for the same purpose, which is the use of GOTO :EOF. Let’s see an example with this new method.

@echo off
GOTO :EOF
ECHO This line will not execute

GOTO :EOF works in the same way that EXIT works. GOTO :EOF immediately closes the current running script, and the line ECHO This line will not execute will remain unexecuted.

Use Both EXIT and GOTO :EOF to Exit a Batch File

Moreover, we can combine EXIT and GOTO :EOF in the same script. Let’s see an example and its explanation to make it more clear.

@echo off
CALL :GetErrorLevel
ECHO The error level is  - %errorlevel%
GOTO :EOF

:GetErrorLevel
EXIT /B 1

In this example, we first made a function call to GetErrorLevel with the line CALL :GetErrorLevel. In the function GetErrorLevel, we just created an EXIT command with an error level of 1.

With the line, ECHO The error level is - %errorlevel%, we just printed the error level. Lastly, we terminated the current script using the line GOTO :EOF.

The output of this code should look like the following:

The error level is - 1

Remember, all methods discussed here are written using Batch Script and will only work in a Windows CMD environment.

MD Aminul Islam avatar MD Aminul Islam avatar

Aminul Is an Expert Technical Writer and Full-Stack Developer. He has hands-on working experience on numerous Developer Platforms and SAAS startups. He is highly skilled in numerous Programming languages and Frameworks. He can write professional technical articles like Reviews, Programming, Documentation, SOP, User manual, Whitepaper, etc.

LinkedIn