In DOS, OS/2, and also Microsoft Windows, batch file is the name given to a type of
script file, a text file containing a series of commands to be executed by the command
interpreter. A batch file may contain any command the interpreter
accepts interactively at the command prompt. A batch file may also have constructs that
enable conditional branching and looping within the batch file.
Similar to job control language and other systems on mainframe and minicomputer systems,
batch files were added to ease the work required for certain regular tasks by allowing the
user to set up a script to automate them. When a batch file is run, the shell program
reads the file and executes its commands, normally line-by-line. Unix-like operating
systems have a similar, but more flexible, type of file called a shell script.
The filename extension .bat was used in DOS, and the Windows 9x family of operating systems.
The Microsoft Windows NT-family of operating systems and OS/2 added .cmd. Batch files for
other environments may have different extensions, e.g. .btm in 4DOS, 4OS2 and 4NT related shells.
There have been changes to the detailed handling of batch files; some of the detail in this
article is applicable to all batch files, while other details apply only to certain
versions.
Variants DOS
In MS-DOS, a batch file can be started from the command line by typing its name followed
by any required parameters and pressing the "enter" key. When MS-DOS loads, the file AUTOEXEC.BAT
is automatically executed, so any commands that need to be run to set up the MS-DOS environment
for use could be placed in this file. Computer users would have the autoexec file set up
the system date and time, initialize the MS-DOS environment, load any resident programs or
device drivers, or initialize network connections and assignments.
In MS-DOS, the extension ".BAT" identified a file containing commands which could be
executed by the command interpreter COMMAND.COM line by line as if it was a list of commands
to be entered, with some extra batch-file-specific commands for basic programming functionality,
including a GOTO command for changing flow of line execution.
Early Windows Microsoft Windows was introduced in 1985 as
a GUI-based alternative to text-based operating systems and was designed to run on MS-DOS.
In order to start it, the WIN command was used and could be added to the end of the
AUTOEXEC.BAT file to allow automatic loading of Windows. In the earlier versions one could
run a .bat type file from Windows in the MS-DOS Prompt.
Windows was run from MS-DOS and used COMMAND.COM to run .bat files on the following operating
systems: Windows 1, 2 and 3.
Windows 95 and 98. Windows ME.
OS/2 The IBM OS/2 operating system supported DOS-style
batch files. It also included a version of REXX, which was a more advanced batch-file
scripting language. IBM and Microsoft started developing this system, but during the construction
of it broke up after a dispute; as a result of this, IBM referred to their MS-DOS-like
console shell without mention of Microsoft, naming it just DOS, although this seemingly
made no difference with regard to the way batch files worked from COMMAND.COM.
OS/2's batch file interpreter also supports an EXTPROC command. This passes the batch
file to the program named on the EXTPROC file as a data file. The named program can be a
script file; this is similar to the #! mechanism. Windows NT
Windows versions other than the NT line of operating systems were run from MS-DOS and
used the same command interpreter, COMMAND.COM, to execute batch files. However, the operating
systems in the Windows NT series run directly upon booting the hard drive; they are true
operating systems, not graphical user interfaces for underlying MS-DOS. An enhanced 32-bit
command processor, cmd.exe, was introduced; it could execute scripts with either the .CMD
or .BAT extension. Cmd.exe added additional commands, and implemented existing ones in
a slightly different way, so that the same batch file might work differently with cmd.exe
and COMMAND.COM. In most cases, operation is identical if the few unsupported commands
are not used. Cmd.exe's extensions to COMMAND.COM can be disabled for compatibility.
Microsoft released a version of cmd.exe for Windows 9x and ME called WIN95CMD to allow
users of older versions of Windows to use certain cmd.exe-style batch files.
As of Windows 8, cmd.exe is the normal command interpreter for batch files; the older COMMAND.COM
can be run from within a cmd.exe window in 32-bit versions of Windows able to run 16-bit
programs. Filename extensions
.bat: The first filename extension used by Microsoft for batch files. This extension
runs with MS-DOS and all versions of Windows, under COMMAND.COM or cmd.exe, despite the
different ways the two command interpreters execute batch files.
.cmd: Used for batch files in Windows NT family and sent to cmd.exe for interpretation. COMMAND.COM
does not recognize this filename extension, cmd.exe scripts are not executed in the wrong
Windows environment by mistake. In addition, "set", "path", "assoc" and "prompt" commands,
when executed from a .bat file, alter the value of the "errorlevel" variable only upon
an error, whereas from within a .cmd file, they would affect errorlevel even when returning
without an error. It is also used by IBM's OS/2 for batch files.
.btm: The extension used by 4DOS and 4NT. The scripts that run on 4DOS and 4NT are faster,
especially with longer ones, as the script is loaded entirely ready for execution, rather
than line-by-line. Example
This example batch file displays "Hello World!", prompts and waits for the user to press a
key, and then terminates.
To execute the file, it must be saved with the extension .bat in plain text format, typically
created by using a text editor such as Notepad or a word processor in text mode.
Result When executed, this is displayed:
Explanation The interpreter executes each line in turn,
starting with the first. The @ symbol at the start of the line prevents the prompt from
displaying that command. The command ECHO off turns off the prompt permanently, or until
it is turned on again. Then the next line is executed and the ECHO Hello World! command
outputs Hello World!, as only off and on have special functions. Then the next line is executed
and the PAUSE command displays Press any key to continue . . . and pauses the script's
execution. After a key is pressed, the script terminates, as there are no more commands.
In Windows, if the script is run within a Command Prompt window, the window remains
open at the prompt as in MS-DOS, otherwise the command prompt window closes on termination.
Limitations and exceptions Null values in variables
Variable expansions are substituted textually into the command, and thus variables which
contain nothing simply disappear from the syntax, and variables which contain spaces
turn into multiple tokens. This can lead to syntax errors or bugs.
For example, if %foo% is empty, this statement:
parses as the erroneous construct:
Similarly, if %foo% contains "abc def", then a different syntax error results:
The usual way to prevent this problem is to surround variable expansions in quotes so
that an empty variable expands into the valid expression IF ""=="bar" instead of the invalid
IF ==bar. The text that is being compared to the variable must also be enclosed in quotes,
because the quotes are not special delimiting syntax; these characters represent themselves.
The delayed !VARIABLE! expansion available in Windows 2000Vista/7 may be used to avoid
these syntactical errors. In this case, null or multi-word variables will not fail syntactically
because the value will be expanded after the IF command is parsed:
Another difference in Windows 2000Vista/7 or higher is that an empty variable is not
substituted. As described in previous examples, previous batch interpreter behaviour would
have resulted in an empty string. Example:
Batch interpreters prior to Windows 2000Vista/7 would have displayed result "MyVar is Not
defined" Quotation marks and spaces in passed strings
For some commands, spaces are treated as delimiters in commands, unless those spaces are enclosed
by quotation marks. A single quotation mark is not included as part of the string. However,
an escaped quotation mark can be part of the string.
For other commands, spaces are not treated as delimiters and do not need quotation marks.
If quotes are included they become part of the string.
This can cause conflicts where a string contains quotation marks, and is to be inserted into
another line of text that must also be enclosed in quotation marks:
Under Windows 2000Vista/7, the solution is to replace each occurrence of a quote character
within a value by a series of three quote characters:
Escaped characters in strings Some characters, such as pipe characters,
have special meaning to the command line. They cannot be printed as text using the ECHO
command unless escaped using the caret ^ symbol:
However, escaping does not work as expected when inserting the escaped character into
an environment variable. The variable ends up containing a live pipe command when merely
echoed. It is necessary to escape both the caret itself and the escaped character for
the character display as text in the variable:
The delayed !VARIABLE! expansion available with CMD /V:ON or with SETLOCAL ENABLEDELAYEDEXPANSION
in Windows 2000Vista/7 may be used to show special characters stored in environment variables
because the variable value will be expanded after the command was parsed:
Sleep or scripted delay The PAUSE command halts script activity indefinitely
until a key is pressed; small programs and workarounds were written to implement a timed
pause. Many workarounds using scripting commands only worked in some environments: the CHOICE
command was not available in older DOS versions, PING was only available if TCP/IP was installed,
and so on. Simple small programs were readily available; a typical example is the 94-byte
WAIT.COM executable. WAIT 5 would wait for 5 seconds, then return control to the script.
Most such programs are 16-bit .COM files incompatible with 64-bit Windows, but they have not been
needed since Windows Vista introduced the TIMEOUT command.
Text output with stripped CR/LF Normally all printed text automatically has
the control characters for "carriage return" and "line feed" appended to the end of each
line.
It does not matter if the two echo commands share the same command line; the CR/LF codes
are inserted to break the output onto separate lines:
A trick discovered with Windows 2000Vista/7 is to use the special prompt for input to
output text without CR/LF trailing the text. In this example, the CR/LF does not follow
Line 1, but does follow Line 2 and Line 3:
This can be used to output data to a text file without CR/LF appended to the end:
However, there is no way to inject this stripped CR/LF prompt output directly into an environment
variable. Setting a UNC working directory from a shortcut
It is not possible to have a command prompt that uses a UNC file path as the current working
directory, like this:
The command prompt requires the use of drive letters to assign a working directory, which
makes running complex batch files stored on a server UNC share more difficult. While a
batch file can be run from a UNC file path, the working directory will default to "C:\windows\system32\"
In Windows 2000Vista/7, a workaround is to use the PUSHD and POPD command with command
extensions. Quoting the help for PUSHD in Windows 7, If Command Extensions are enabled
the PUSHD command accepts network paths in addition to the normal drive letter and path.
If a network path is specified, PUSHD will create a temporary drive letter that points
to that specified network resource and then change the current drive and directory, using
the newly defined drive letter. Temporary drive letters are allocated from Z: on down,
using the first unused drive letter found. If not enabled by default, command extensions
can be temporarily enabled using the "/E:ON" switch for the command interpreter.
So to run a batch file on a UNC share, assign a temporary drive letter to the UNC share,
and use the UNC share as the working directory of the batch file, a Windows shortcut can
be constructed that looks like this:
The working directory attribute of this shortcut is ignored.
The following syntax does correctly expand to the path of the current batch script.
%~dp0
Character set Batch files use a DOS character set, as defined
by the computer, e.g. Code page 437. The non-ASCII parts of these are incompatible with the Unicode
or Windows character sets otherwise used in Windows so care needs to be taken. Non-English
file names work only if entered through a DOS character set compatible editor. File
names with characters outside this set won't work in batch files.
To get output in Unicode into file pipes from an internal command such as dir, one can use
the cmd /U command. For example cmd /U /C dir > files.txt will create a file containing
a directory listing with correct Windows characters, in the UTF-16LE encoding.
Batch viruses and malware Batch files can be used to write malware and
viruses. Some well-known examples in the hacking community are the window bomber malware which
opens the same program so many times the computer is exhausted from resources, the neverending
copying of the batch file all over the disk, or the DNS poisoning malware in which the
batch file modifies the hosts file file to make a Windows computer connect to an IP address
specified by the batch file's programmer when the user attempts to visit the website of
a well-known internet site unrelated to the malware. Batch viruses can also spread themselves
via USB flash drives by using Windows' Autorun capability.
Other Windows scripting languages The cmd.exe command processor that interprets
.cmd files is supported in all 32- and 64-bit versions of Windows up to at least the 2011
Windows 8 preview. COMMAND.EXE, which interprets .BAT files, was supported in all 16- and 32-bit
versions up to at least Windows 8 preview. While the more powerful 2006 Windows PowerShell
is favored in later versions of Windows that support it, Microsoft was also using .cmd
files as far as, at least, Windows Server 2008. An example is servermanagercmd.exe which
incorporates the entire set of Server Manager functions for Windows Server 2008.
There are other, later and more powerful, scripting languages available for Windows.
However, these require the scripting language interpreter to be installed before they can
be used: KiXtart - developed by a Microsoft employee
in 1991, specifically to meet the need for commands useful in a network logon script
while retaining the simple 'feel' of a .cmd file.
Windows Script Host - released by Microsoft in 1998, and consisting of cscript.exe and
wscript.exe, runs scripts written in VBScript or JScript. It can run them in windowed mode
or in console-based mode. They have been a part of Windows since Windows 98.
Windows PowerShell - released in 2006 by Microsoft and can operate with Windows XP and later
versions. PowerShell can operate both interactively and also via saved scripts, and has a strong
resemblance to Unix shells. Unix-style shell scripting languages can be
used if a Unix compatibility tool, such as Cygwin, is installed.
Cross-platform scripting tools including Perl, Python, Ruby and Rexx and PHP are available
for Windows. Script files will run if the filename without
extension is entered. There are rules of precedence governing interpretation of, say, DoThis if
DoThis.cmd, DoThis.bat, DoThis.exe, etc. exist; by default DoThis.cmd has highest priority.
This default order may be modified in newer operating systems by the user-settable PATHEXT
environment variable. See also
Batch job List of DOS commands
Shell script - UNIX equivalent References
External links Microsoft Windows XP Batch file reference
How Windows batch files work Windows batch file command overview
Batfiles: The DOS batch programming handbook FreeDOS' FreeCOM : complete feature list
MS-DOS+Win..98/ME batch programming links Windows Command Line Interface script programming
links scripting related information