Stopping a DOS batch file

This article is from our Febooti archive, it was relevant then, and I think that it is still relevant today (a few details changed).
Previous article: First cmd / DOS batch script example.

Usually, OS (Windows, MS-DOS) executes a batch file without stopping. DOS stops processing the batch file while the program runs when the batch file loads a program. As soon as you exit the program, or an automatic termination occurs, OS immediately continues processing the batch file from where it left off. Typically this is what you want, but sometimes you want to give the user time to think, react, and then take action. An example would be giving the user a group of choices that you want them to select from before proceeding.

PAUSE is the command we are looking for. PAUSE stops the batch file until almost any key is pressed. A key that would produce a character on the screen needs to be pressed. Therefore pressing a key like CTRL or ALT or SHIFT will not exit out of the pause state. Earlier we used this command above to see the output on the console. Now we will use this to pause the execution of the batch script.

Though the PAUSE command is really quite helpful, it lacks in power. The keystroke that you press is not capable of being used as a menu selection nor can it be saved in the program in any other way. Below is an example to illustrate how the PAUSE command works along with the ways of terminating a program with the keyboard.

:: PAUSE-IT.bat
:: Example of the PAUSE command
:: and the ways to exit out of a program.
@ECHO OFF
ECHO The next command is a PAUSE
ECHO Do NOT press Ctrl+C or Ctrl+Break
PAUSE
ECHO Press Ctrl+C or Ctrl+Break on your keyboard
PAUSE

The first line is a comment with the name of the file. The second and third line comments are description of the program (batch file). The fourth line turns command-echoing off. Line 5 and 6 gives the first message about which keys you can press for the first example. Line 7 is the PAUSE command that stops the batch file until a key is pressed. The next line (8) displays the message about aborting the program using the keyboard controls. The last line (9) is the final PAUSE that finishes the program.

You can terminate this script in many ways, however, if you follow the ECHO instructions, then you will have the following output:

Batch file: press CTRL+Break CTRL+C
Batch file: press CTRL+Break CTRL+C

As you see in the screenshot, after pressing Ctrl+Break or Ctrl+C, the command interpreter asks you to “Terminate batch job (Y/N)?”. By pressing Y followed by the Enter, the batch file terminates.

Next article: Replaceable parameters in batch file.

UPDATE: Jan 15, 2015… added link to the next article.

This article is from our Febooti archive, it was relevant then, and I think that it is still relevant today (a few details changed).

Leave a Reply

Your email address will not be published.