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 MS-DOS commands that are to be run, typically 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 double-click on the batch file from Windows and the batch file will be run.

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

To run a batch file from the command prompt, type its filename, e.g.: hello.bat. To run a batch file from Windows, double-click its file icon.

When you run a batch file, MS-DOS will display each command just before it is run. That way if something does not work you can see what commands were run. 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.

Beyond the typical MS-DOS commands, some commands that are especially useful in batch files are:

  • for
    Looping 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 preexists 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. You can alter normal execution 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 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 (e.g.: echo Press Enter to copy file). See: help pause

  • echo
    Displays the specified message, e.g.: echo Press Enter to copy file. See: help echo