MS-DOS Commands :: Batch Files


Note: Advanced programming of batch files is beyond the scope of this document.

The general concept of batch files is that they are a text file that contains a sequence commands that are to be run in order, starting at the first line and continue to the last line. For example, you could create a batch file that copies a group of files to your USB memory stick. You can then click on the batch file from Windows and the batch file will be run.

Batch files are regular text files but they have a filename ending with .bat rather than .txt. Since they are text files, you can create them using any plain text editor such as Windows Notepad editor. To run Notepa, select Notepad from the Windows start menu or type notepad at the command prompt.

To run a batch file, simply type its filename, e.g.: hello.bat

When you run a batch file, MS-DOS will display each command before it is run. That way if something does not work you can see what went wrong. If you do not want the commands echoed, at the start of your batch file add the line: @echo off

To stop a batch file before it finishes, press Ctrl-C. When prompted with "Terminate batch job (Y/N)?" asking whether you want to stop the batch file, press the y key followed by the Enter key.

You can put any commands into a batch file. Beyond the typical commands, some commands that are espcially useful in batch files are:

  • for
    Loop construct so you can run a command on multiple files. For help, type: help for

  • if
    Conditionally run a command based on a specified test condition, such as whether a specified file pre-exists or not. For help, type: help if

  • goto
    Normally, a batch file is run "top to bottom" one line at a time, starting at the first line and continuing until the last line is reach. You can alter normal executiion flow so execution continues at the specified named line instead of the next line. The goto is typically used as part of an if command, e.g.: if not exist mystuff.txt goto error. For help, type: help goto

  • call
    Calls one batch program file from another. See: call.

  • pause
    Pauses execution and displays the message "Press any key to continue . . .". Pressing any key (e.g.: spacebar, Enter, Esc, etc.) will cause program execution to resume. However, if Ctrl-C is pressed, execution will terminate. Typically used following an echo that displays some warning (echo Press Enter to delete file / pause). See: help for

  • echo
    Displays the specified messages. See: help for