- Batch file
-
This article is about DOS, OS/2 and Windows scripting. For other types of batch programming, see shell script.
Batch file Filename extension .bat .cmd .btm
Type of format Scripting Container for Shell scripts In DOS, OS/2, and Microsoft Windows, a batch file is a text file containing a series of commands intended to be executed by the command interpreter.
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 (usually COMMAND.COM or cmd.exe) reads the file and executes its commands, normally line-by-line.[1] Unix-like operating systems (such as Linux) have a similar type of file called a shell script.[2]
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, but batch files for other environments may have different extensions, e.g. .btm in 4DOS and 4NT related shells.
Contents
Variants
In MS-DOS, a batch file can be started from the command line by typing its name (along with 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.
DOS
In MS-DOS, the extension ".bat" signified a file which could be executed by the command interpreter COMMAND.COM, by running 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 Operating System alternative to text-based operating 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 (access to real mode MS-DOS was restricted).
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 on 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 from booting the hard drive and aren't based on MS-DOS. In order to replace COMMAND.COM, cmd.exe was introduced which allowed execution of .cmd files as well as .bat files in the same way, and used slightly different commands than COMMAND.COM, meaning that the new cmd.exe was not backwards compatible with older batch files for use with COMMAND.COM.
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.
Currently, cmd.exe is the command interpreter for batch files on the latest version of Windows.
Filename extensions
- .bat: The first 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: The extension used by operating systems in the Windows NT family and sent to cmd.exe for interpretation. It does not work on computers relying on COMMAND.COM so prevents cmd.exe scripts from being executed in the wrong Windows environment. It is also used by IBM's OS/2 for batch files.
- .btm: The extension used by 4DOS and 4NT. The scripts 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.[3]
Differences between .cmd and .bat execution in the Windows NT family
The only known difference between .cmd and .bat file execution is that in a .cmd file the
ERRORLEVEL
variable changes even on a successful command that is affected by Command Extensions (when Command Extensions are enabled), whereas in .bat files theERRORLEVEL
variable changes only upon errors.[4]Example
This example batch file is a simple program that displays a hello world program and then waits for the user to press a key before ending.
@ECHO off ECHO Hello World! PAUSE @ECHO on
To execute the file it must be saved with a .bat or .cmd extension in plain text format (with a program like Notepad).
Result
When executed (either from Windows Explorer or Command Prompt) this is displayed:
Hello World! Press any key to continue . . .
Explanation
The interpreter executes each line in turn, starting with the first. The
@
symbol at the start of the line turns off the prompt from displaying that command. The commandECHO off
turns off the prompt permanently, or until it is turned on again. Then the next line is executed, theECHO Hello World!
command outputsHello World!
, as onlyoff
andon
have special functions. Then the next line is executed, thePAUSE
command literally 'pauses' the script's execution, and displays the outputPress any key to continue . . .
. After a key is pressed, the script continues onto the next line,ECHO on
, which turns the prompt back on for use. Then the end of the script is reached so execution stops. If the script started from the Command Prompt, then it will remain open at the prompt. If the script started from Windows Explorer, then upon finishing the window will close.Advanced batch example - conditional shutdown
@echo off color 3 title Conditional Shutdown set /p name="enter a name:" :start cls echo Hi, %name% echo. echo 1.Shutdown echo 2.Quit :invalid_choice set /p choice="enter your choice 1,2: " if %choice%==1 goto shutdown if %choice%==2 exit echo invalid choice: %choice% goto invalid_choice :shutdown cls set /p sec="enter the number of seconds that you wish the computer to shutdown in: " set /p message="enter the shutdown message you wish to display: " shutdown -s -f -t %sec% -c "%message%" echo shutdown initiated at %time% set /p cancel="type cancel to stop shutdown " if %cancel%==cancel shutdown -a if %cancel%==cancel goto start
Limitations / 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 leads to syntax errors or bugs.
For example:
IF %foo%==bar ECHO Equal
if %foo% is empty, parses as the erroneous construct:
IF ==bar ECHO Equal
and if %foo% contains "abc def", then the syntax is also wrong:
IF abc def==bar ECHO Equal
The traditional way to anticipate and prevent this problem is to surround variable expansions in quotes. 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.
IF "%foo%"=="bar" ECHO Equal
The delayed !VARIABLE! expansion available in Windows 2000/XP/Vista/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:
IF !foo!==bar ECHO Equal
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 one-character 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 don't 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:
C:\> Set foo="this string is enclosed in quotation marks" C:\> Echo "test 1 %foo%" "test 1 "this string is enclosed in quotation marks"" C:\> Eventcreate /T Warning /ID 1 /L System /SO "Source" /D "Example: %foo%" ERROR: Invalid Argument/Option - 'string'. Type "EVENTCREATE /?" for usage.
Under Windows 2000/XP/Vista/7, the solution is to do a search and replace on the one character quote and replace it with three quotes:
C:\> Set foo="this string is enclosed in quotes" C:\> Set foo=%foo:"="""% C:\> Echo "test 1 %foo%" "test 1 """this string is enclosed in quotes"""" C:\> Eventcreate /T Warning /ID 1 /L System /SO "Source" /D "Example: %foo%" SUCCESS: A 'Warning' type event is created in the 'Source' log/source.
Escaped characters in strings
Some characters have special meaning to the command line, such as the pipe | character. These can not be printed as text using the ECHO command unless it is escaped using the caret ^ symbol:
C:\> Echo foo | bar 'bar' is not recognized as an internal or external command, operable program or batch file. C:\> Echo foo ^| bar foo | bar
However, escaping does not work as expected when inserting the escaped character into an environment variable, and 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:
C:\> set foo=bar | baz 'baz' is not recognized as an internal or external command, operable program or batch file. C:\> set foo=bar ^| baz C:\> echo %foo% 'baz' is not recognized as an internal or external command, operable program or batch file. C:\> set foo=bar ^^^| baz C:\> echo %foo% bar | baz
The delayed !VARIABLE! expansion available in Windows 2000/XP/Vista/7 may be used to show special characters stored in environment variables because the variable value will be expanded after the command was parsed:
C:\> set foo=bar ^| baz C:\> echo !foo! bar | baz
Sleep / Scripted Delay
The PAUSE command halts script activity indefinitely, but until Windows Vista/7 introduced the TIMEOUT command there was no obvious way to introduce a simple timed pause. This lack lead to a number of ingenious workarounds, including:[5]
REM Wait 10 seconds... choice /ty,10
Note that choice is not always available.
REM Wait 12 seconds.. ping -n 13 127.0.0.1 > nul
Which pings the local computer via the loopback address (127.0.0.1) so only works when TCP/IP and associated commands are installed. The -n parameter is 13 because there is a one-second delay between pings
@echo off for /f "tokens=1-3 delims=:.," %%a in ("%time%") do set /a h=%%a, m=1%%b%%100, s=1%%c%%100, end=(h*60+m)*60+s+%1 :wait for /f "tokens=1-3 delims=:.," %%a in ("%time%") do set /a h=%%a, m=1%%b%%100, s=1%%c%%100, current=(h*60+m)*60+s if %current% lss %end% goto wait
Using extended features of the for command and so only works in the later Windows 2000/XP/Vista/7 - and fails if the delay interval crosses midnight.
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.
batchtest.bat: @echo foo @echo bar C:\>batchtest.bat foo bar
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:
C:\> @echo foo&@echo bar foo bar
A trick discovered with Windows 2000/XP/Vista/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:
batchtest.bat: @echo off set foo=Line 1 echo y | set /p tmp="%foo%" echo Line 2 echo Line 3 C:\>batchtest.bat Line 1Line 2 Line 3 C:\>
This can be used to output data to a text file without CR/LF appended to the end:
C:\> echo y | set /p tmp="Line 1"> data.txt C:\> echo y | set /p tmp="Line 2">> data.txt C:\> echo y | set /p tmp="Line 3">> data.txt C:\> type data.txt Line 1Line 2Line 3
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:
\\server\share\directory\>
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 2000/XP/Vista/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:
Target: %COMSPEC% /E:ON /C "PUSHD """\\SERVER\SHARE\DIR1\DIR2\""" & BATCHFILE.BAT & POPD"
The working directory attribute of this shortcut is ignored.
Future
Microsoft has not officially released information regarding the future of the command prompt that hosts .bat and .cmd files.
While the more powerful Windows PowerShell is favored in their newer operating systems, Microsoft is still making new utilities for the classic command prompt. (An example is servermanagercmd.exe[6] which incorporates the entire set of Server Manager functions for Windows Server 2008).
Other Windows scripting-languages
In addition to traditional batch files, the need for more powerful capabilities has led to the development of other Windows-specific scripting languages:
- KiXtart (.kix) - 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 the traditional batch file.
- Windows Script Host (.vbs and .js) - released in 1998, (consisting of cscript.exe and wscript.exe) runs scripts written in VBScript or JScript. It can run them in windowed mode (with the wscript.exe host) or in console-based mode (with the cscript.exe host). They have been a part of Windows since Windows 98.
- Windows PowerShell (.ps1) - released in 2006 by Microsoft and can operate with Windows XP (SP2/SP3) and above. PowerShell can operate both interactively (from a command-line interface) and also via saved scripts, and has a strong resemblance to Unix shells.[7]
In addition to these, as of 2010[update] cross-platform scripting tools such as Perl, Python, Ruby and Rexx can run under Windows.
If the appropriate extension is set in the PATHEXT environment, script files will run without need of typing in their extension.
See also
- VBScript
- JScript
- Windows PowerShell, extensible command-line shell released in 2006
- List of DOS commands
- Shell script - UNIX equivalent
References
- ^ http://technet.microsoft.com/en-us/library/cc758944(WS.10).aspx
- ^ http://www.file-extensions.org/bat-file-extension
- ^ http://www.cryer.co.uk/filetypes/b/btm.htm
- ^ http://groups.google.com/group/microsoft.public.win2000.cmdprompt.admin/msg/ad9066638815812c
- ^ "How to do a delay", ericphelps.com
- ^ http://www.winsupersite.com/showcase/win2008_cli.asp
- ^ http://geekswithblogs.net/sdorman/archive/2006/06/18/82258.aspx
External links
Categories:- Scripting languages
- DOS on IBM PC compatibles
- Windows administration
Wikimedia Foundation. 2010.