Windows command line exit

The `exit` command in CMD is used to close the Command Prompt window or exit a batch script.

exit

What is the `exit` Command?

The `exit` command is a vital component of the Command Prompt (CMD) environment. It serves primarily to close the current CMD session or terminate batch files and scripts. Understanding how to effectively utilize this command is crucial for anyone looking to harness the full power of CMD.

Reset IP Cmd: Your Quick Guide to Network Refresh

Reset IP Cmd: Your Quick Guide to Network Refresh

How to Use the `exit` Command

Basic Syntax

The basic syntax for the `exit` command is straightforward:

exit [exit_code]

Here, the optional `exit_code` allows you to specify a numeric code that indicates the status of the process being terminated. If no exit code is provided, the default behavior simply exits the session with a status of zero, which typically signifies success.

Exiting the Command Prompt

Using the `exit` command to terminate a CMD session is easy and efficient. Simply type `exit` in the command prompt and press Enter. This will close the CMD window.

For example:

C:\> exit

Upon using this command, you will find that the command prompt window closes immediately. It is essential to note that while closing a CMD window can be done with the ‘X’ button, using the `exit` command is a cleaner way to exit, especially when operating in scripts or batch files.

Exiting a Batch File

In the context of batch files, the `exit` command is used to end script execution. This helps manage flow control and indicates the completion status of the script.

The syntax to exit a batch file while returning an exit code is:

exit /B [exit_code]

This `/B` switch allows the exit code to be returned to the calling batch file or command prompt. Here’s an example of using `exit` in a batch file:

@echo off
echo Running a batch file...
exit /B 0

In this case, the script runs a simple echo command and then exits with a status of `0`, indicating successful execution.

Using Rem in Cmd: A Quick Guide to Comments

Using Rem in Cmd: A Quick Guide to Comments

Exit Codes: What They Mean

Understanding Exit Codes

Exit codes are numeric values used to indicate the result of a command or a script execution. They are crucial for diagnosing run-time status, especially in larger, more complex scripts where knowing the state of execution is essential.

Common exit codes include:

  • `0`: Indicates that the operation was successful.
  • `1`: Denotes a generic error.
  • Other values can be defined by developers to indicate specific conditions.

Setting and Retrieving Exit Codes

Setting an exit code when using the exit command can be done like this:

exit /B 0

Checking the exit codes is equally important after script execution. Here’s a quick example:

@echo off
echo Task completed
exit /B 1

In this case, the script signals a task’s completion but indicates an error with exit code `1`. Tracking these codes allows users to implement error handling in their scripts, improving overall reliability.

Mastering Grep in Cmd: A Quick Guide

Mastering Grep in Cmd: A Quick Guide

Scenarios for Using the `exit` Command

Exiting After a Successful Operation

To enhance script functionality, the `exit` command can be strategically used after successful operations. Here’s an example that checks for a file’s existence:

if exist "file.txt" (
  echo File exists!
  exit /B 0
) else (
  echo File not found!
  exit /B 1
)

In this scenario, the script verifies if «file.txt» exists in the current directory. It uses `exit /B` to return a success code if the file is found and an error code if it is not.

Implementing in Scripts

Effective use of the `exit` command can help creators manage script execution flow. Strategic placement allows for enhanced error handling and debugging. For example:

@echo off
call another_script.bat
if errorlevel 1 (
  echo There was an error!
  exit /B 1
)
exit /B 0

Here, the primary script calls another script and checks the exit status of that script. If it fails (returning an exit code of `1`), it outputs an error message and exits with the same error status.

Mastering User in Cmd: A Simple Guide

Mastering User in Cmd: A Simple Guide

Common Mistakes and Tips

Common Errors

One common mistake made by CMD users involves misunderstanding the purpose of the `exit` command. Specifically, forgetting to include the `/B` switch in scripts can lead to unexpected behavior:

if %var%==value exit

Without `/B`, this would cause the whole CMD session to terminate instead of just the script.

Best Practices

To avoid common pitfalls, it is essential to always document exit codes used in scripts. This documentation will clarify the significance behind each code, making it easier for others (and your future self) to understand the flow of the script.

Additionally, keeping commands modular and well-organized allows for more efficient exit handling. For instance, breaking down code into functions that systematically use the `exit` command can save time during both development and troubleshooting.

Trace in Cmd: A Simple Guide to Network Diagnostics

Trace in Cmd: A Simple Guide to Network Diagnostics

Recap of Key Points

Understanding the `exit` command in CMD is crucial for effective command-line operation. It allows users to control the flow of their scripts and manage error handling with ease. Utilizing exit codes can greatly enhance the efficiency of scripts, paving the way for better debugging and maintenance processes.

Mastering Msconfig in Cmd: A Quick Guide to System Tweaks

Mastering Msconfig in Cmd: A Quick Guide to System Tweaks

Conclusion

Mastering the `exit` command in CMD will significantly improve your command-line efficiency. By understanding how to use this command effectively, you set yourself on a path to becoming adept at scripting and automating tasks. Don’t hesitate to practice using `exit` commands in your CMD sessions and explore more resources to grow your CMD expertise.

  • SS64
  • CMD
  • How-to

Close the CMD.EXE session or optionally close only the current batch script (/b). EXIT can also set an ERRORLEVEL.

Syntax
      EXIT [/B] [exitCode]

Key
    /B        When used in a batch script, this option will exit the current script
              or subroutine but not CMD.EXE

   exitCode   Sets the %ERRORLEVEL% to a 32 bit numeric number.
              If quitting CMD.EXE, this will set the process exit code.
              The number can be up to 2147483647.

To close an interactive command prompt, the keyboard shortcut ALT + F4 is an alternative to typing EXIT.

If you CALL one batch file from another and the second script uses an EXIT /B command, then execution of the second script will terminate and the first batch script will continue.

If you CALL (not GOTO) a subroutine within the main batch file and the subroutine uses an EXIT /B command, then execution of the subroutine will terminate and the batch script will continue from the point where it was CALLed (at the next line after the initial CALL).

If EXIT without /B is used within a subroutine, then it will terminate the entire batch script.

If EXIT or EXIT /B are executed directly from the command-line the CMD.exe session will be closed.

Errorlevel

EXIT /b has the option to set a specific exit code, EXIT /b 0 for sucess, EXIT /b 1 (or greater) for an error.

The error code will be returned to the calling process even if SETLOCAL has been set

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% system variable, (SET ERRORLEVEL n ) instead use EXIT /b n as a safe way to set the internal ERRORLEVEL 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 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.

Examples

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

Set the errorlevel to 5:

@Echo Off
Call :setError
Echo %errorlevel%
Goto :eof

:setError
Exit /B 5

Run a batch file which exits with an error and then display it. In these examples throw_err.cmd does nothing other than exit with error #3:

C:\> Echo @exit /b 3 > throw_err.cmd
C:\> CMD /c throw_err.cmd && echo Success || echo Error: %errorlevel%
1 C:\> CMD /K throw_err.cmd && echo Success || echo Error: %errorlevel% C:\> exit 3 C:\> Echo @exit 3 > throw_err.cmd C:\> CMD /c throw_err.cmd && echo Success || echo Error: %errorlevel%
3 From PowerShell (this works with or without /b): PS C:\> ./throw_err.cmd PS C:\> $lastExitCode 3

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:

@Echo Off
Setlocal 
For %%A in (alpha beta gamma) DO (
   Echo Outer loop %%A
   Call :inner 
)
Goto :eof

:inner
For %%B in (U V W X Y Z) DO (
   if %%B==X ( exit /b 2 )
   Echo    Inner loop    Outer=%%A Inner=%%B
)

“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” ~ Fiona Apple

Related commands

VERIFY — Provides an alternative method of raising an error level without exiting.
TSKILL — End a running process.
TITLE — Set the window Title / Display the number of nested CMD sessions.
Equivalent PowerShell: Exit — Exit PowerShell or break — Exit a program loop.
Equivalent bash command (Linux): break — Exit from a loop.


Copyright © 1999-2025 SS64.com
Some rights reserved

  1. Step 1 Type exit in the console.

  2. Step 2 Hit ↵ Enter.

    The Command Prompt window in which the command was typed will close.

  3. Advertisement

  1. Step 1 Look at the three window control buttons at the top-right corner of the Command Prompt window.

  2. Step 2 Click the "X" button to close it.

    If you’re using Windows 10, the button will be white until highlighted with your pointer.

  3. Advertisement

Add New Question

  • Question

    How do I get on CMD using a Mac?

    Type exit, or click the x in the upper right hand corner, You can also right click on the top banner and select, close.

Ask a Question

200 characters left

Include your email address to get a message when this question is answered.

Submit

Advertisement

Thanks for submitting a tip for review!

About This Article

Thanks to all authors for creating a page that has been read 76,176 times.

Is this article up to date?

Keep up with the latest tech with wikiHow’s free Tech Help Newsletter

Subscribe

You’re all set!

Command Line Commands – CLI Tutorial

The Windows command line is one of the most powerful utilities on a Windows PC. With it, you can interact with the OS directly and do a lot of things not available in the graphical user interface (GUI).

In this article, I’ll show you 40 commands you can use on the Windows command line that can boost your confidence as a Windows user.

N.B.: You have to be careful while using the commands I’ll show you. This is because some commands can have a lasting negative or positive effect on your Windows PC until you reset it.

In addition, some of these commands require you to open the command prompt as an admin.

ss5-1

powershell start cmd -v runAs – Run the Command Prompt as an Administrator

Entering this command opens another command prompt window as an administrator:

ss1-1

driverquery – Lists All Installed Drivers

It is important to have access to all drivers because they often cause problems.

That’s what this command does – it shows you even the drivers you won’t find in the device manager.

ss2-1

chdir or cd – Changes the Current Working Directory to the Specified Directory

ss3-1

systeminfo – Shows Your PC’s Details

If you want to see more detailed information about your system you won’t see in the GUI, this is the command for you.

ss4-1

set – Shows your PC’s Environment Variables

ss5-2

prompt – Changes the Default Text Shown before Entering Commands

By default, the command prompt shows the C drive path to your user account.

You can use the prompt command to change that default text with the syntax prompt prompt_name $G:

ss6-1

N.B: If you don’t append $G to the command, you won’t get the greater than symbol in front of the text.

clip – Copies an Item to the Clipboard

For example, dir | clip copies all the content of the present working directory to the clipboard.

ss7

You can type clip /? and hit ENTER to see how to use it.

assoc – Lists Programs and the Extensions They are Associated With

ss8

title – Changes the Command Prompt Window Title Using the Format title window-title-name

ss9

fc – Compares Two Similar Files

If you are a programmer or writer and you want to quickly see what differs between two files, you can enter this command and then the full path to the two files. For example fc “file-1-path” “file-2-path”.

ss10

cipher – Wipes Free Space and Encrypts Data

On a PC, deleted files remain accessible to you and other users. So, technically, they are not deleted under the hood.

You can use the cipher command to wipe the drive clean and encrypt such files.

ss11

netstat -an – Shows Open Ports, their IP Addresses and States

ss12

ping – Shows a Website IP Address, Lets you Know How Long it Takes to Transmit Data and a Get Response

ss13

color – Changes the Text Color of the Command Prompt

Enter color attr to see the colors you can change to:

ss14

Entering color 2 changes the color of the terminal to green:

ss15

for /f "skip=9 tokens=1,2 delims=:" %i in ('netsh wlan show profiles') do @echo %j | findstr -i -v echo | netsh wlan show profiles %j key=clear – Shows All Wi-Fi Passwords

ss16

ipconfig – Shows Information about PC IP Addresses and Connections

ss17

This command also has extensions such as ipconfig /release, ipconfig /renew, and ipconfig /flushdns which you can use to troubleshoot issues with internet connections.

sfc – System File Checker

This command scans your computer for corrupt files and repairs them. The extension of the command you can use to run a scan is /scannow.

ss18

powercfg – Controls Configurable Power Settings

You can use this command with its several extensions to show information about the power state of your PC.

You can enter powercfg help to show those extensions.

ss19

For example, you can use powercfg /energy to generate a battery health report.

ss20

The powercfg /energy command will generate an HTML file containing the report. You can find the HTML file in C:\Windows\system32\energy-report.html.

dir – Lists Items in a Directory

ss21

del – Deletes a File

ss22

attrib +h +s +r folder_name – Hides a Folder

You can hide a folder right from the command line by typing in attrib +h +s +r folder_name and then pressing ENTER.

To show the folder again, execute the command – attrib -h -s -r folder_name.

ss23

start website-address – Logs on to a Website from the Command Line

ss24

ss25

tree – Shows the Tree of the Current Directory or Specified Drive

ss26

ver – Shows the Version of the OS

ss27

tasklist – Shows Open Programs

You can do the same thing you do with the task manager with this command:

ss28

The next command shows you how to close an open task.

taskkill – Terminates a Running Task

To kill a task, run taskkill /IM "task.exe" /F. For example, taskkill /IM "chrome.exe" /F:

ss29

date – Shows and Changes the Current Date

ss30

time – Shows and Changes the Current Time

ss31

vol – Shows the Serial Number and Label Info of the Current Drive

ss32

dism – Runs the Deployment Image Service Management Tool

ss33

CTRL + C – Stops the Execution of a Command

-help – Provides a Guide to other Commands

For example, powercfg -help shows how to use the powercfg command

ss34

echo – Shows Custom Messages or Messages from a Script or File

ss35

You can also use the echo command to create a file with this syntax echo file-content > filename.extension.

ss36

mkdir – Creates a Folder

ss37

rmdir – Deletes a Folder

ss38

N.B.: The folder must be empty for this command to work.

more – Shows More Information or the Content of a File

ss39

move – Moves a File or Folder to a Specified Folder

ss40

ren – Renames a File with the Syntax ren filename.extension new-name.extension

ss41-1

cls – Clears the Command Line

In case you enter several commands and the command line gets clogged up, you can use cls to clear all entries and their outputs.

cls

exit – Closes the Command Line

shutdown – Shuts down, Restarts, Hibernates, Sleeps the Computer

You can shut down, restart, hibernate, and sleep your PC from the command line.

Enter shutdown in the command line so you can see the extensions you can use to perform the actions. For example, shutdown /r will restart your computer.

ss42

Conclusion

This article showed you several “unknown-to-many” commands you can use to get access to hidden functionalities on your Windows PC.

Again, you should be careful while working with these commands because they can have a lasting effect on your OS.

If you find the commands helpful, share the article with your friends and family.

In case you know another useful command I did not list, tell me about it on Twitter. I will add it and mention you as the source.



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Proxmox драйверы для windows
  • Samsung rv511 драйвера windows 10
  • Asus n61v драйвера windows 10
  • Архив поврежден или имеет неизвестный формат что делать winrar windows 10
  • Сеть загружена на 100 windows 10