Batch file: Difference between revisions
Joey-das-WBF (talk | contribs) |
|||
Line 160: | Line 160: | ||
ping -n 13 127.0.0.1 > nul |
ping -n 13 127.0.0.1 > nul |
||
</source> |
</source> |
||
This necessarily needs to specify one ping |
This necessarily needs to specify one ping more than seconds to wait, since there is a one-second delay ''between'' pings, so this always waits a second less than pings are performed. |
||
Again, TIMEOUT is a better option on Windows Vista/7. |
Again, TIMEOUT is a better option on Windows Vista/7. |
Revision as of 07:42, 17 December 2010
This article needs additional citations for verification. (May 2009) |
Filename extension |
.bat .cmd .btm |
---|---|
Internet media type | application/x-bat |
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 batch script to automate many commands. 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. Batch files are useful for running a sequence of executables automatically and are often used to automate repetitive or tedious processes.[1] Unix-like operating systems (such as Linux) have a similar type of file called a shell script.[2]
DOS batch files have the filename extension .bat. Batch files for other environments may have different extensions, e.g. .cmd or .bat in the Microsoft Windows NT-family of operating systems and OS/2, or .btm in 4DOS and 4NT related shells. The Windows 9x family of operating systems only recognize the .bat extension. In OS/2 a file with a .cmd extension can also be a Rexx file.
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 interpretor 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 the ERRORLEVEL
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 for that command. The command ECHO off
turns off the prompt permanently, or until it is turned on again. Then the next line is executed, the ECHO Hello World!
command outputs Hello World!
, as only off
and on
have special functions. Then the next line is executed, the PAUSE
command literally 'pauses' the script's execution, and displays the output Press 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
set /p choice=enter your choice 1,2:
if %choice%==1 goto shutdown
if %choice%==2 exit
:shutdown
cls
set /p sec=enter the number of seconds that you wish the computer to shutdown in:
set /p msg=enter the shutdown message you wish to display:
shutdown -s -f -t %sec% -c "%msg%"
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
Some commands can fail syntactically and terminate the script, if the variables in the command contain a null value. For example this test will only work properly only if the value of %foo% is 1 character or greater:
IF %foo%==bar ECHO Correct.
But if the value of %foo% is null, the command will evaluate as an invalid command:
IF ==bar ECHO Correct.
The typical way to deal with this is to always enclose the tested variables in quotes, or include some other unchanging character on both sides of the evaluation. For example, these tests are syntactically correct and evaluate as False if %foo% contains a null value:
IF "%foo%"=="bar" ECHO Correct.
IF 1%foo%==1bar ECHO Correct.
A null value in %foo% results in the commands being parsed as:
IF ""=="bar" ECHO Correct.
IF 1==1bar ECHO Correct.
Quotes and spaces in passed strings
- For some commands, spaces are treated as delimiters in commands, unless those spaces are enclosed by quotes. A one-character quote (") is not included as part of the string. However, an escaped quote (""") can be part of the string.
- For other commands, spaces are not treated as delimiters and don't need quotes. If quotes are included they become part of the string.
This can cause conflicts where a string contains quotes, and is to be inserted into another line of text that must also be enclosed in quotes:
C:\> Set foo="this string is enclosed in quotes"
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%"
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.
Sleep / Scripted Delay
The PAUSE command halts script activity indefinitely. For something like "Wait 30 seconds or until a key is pressed" the CHOICE command can be used, with a timeout on the choice selection, like it was possible in MS-DOS already. Alternatively in Windows Vista/7 there is also TIMEOUT which is exactly for this purpose.
A fixed timed delay is also not possible using only batch file commands, but a hack is for the computer to ping itself and pipe the results to NUL (the null device), which results in a delay of 1 second per ping. This only works when TCP/IP and associated commands are installed by default (Windows 2000/XP/Vista/7):
REM Wait 12 seconds..
ping -n 13 127.0.0.1 > nul
This necessarily needs to specify one ping more than seconds to wait, since there is a one-second delay between pings, so this always waits a second less than pings are performed.
Again, TIMEOUT is a better option on Windows Vista/7.
Future
Microsoft has not officially released information pertaining to the future of Command Prompt (host for .bat and .cmd files) yet, but the company is now starting to include Windows PowerShell in releases for newer operating systems, which has all the core functions of Command Prompt and more (and instead of .bat and .cmd files, it runs .ps1 files). Yet it is important to remember that it is not certain this will replace Command Prompt, and that Microsoft is still making important tools for Command Prompt specifically, instead of for PowerShell (such as servermanagercmd.exe
, which incorporates the entire set of Server Manager functions for Windows Server 2008).[5]
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:
- .kix: KiXtart was 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.
- .vbs and .js: Released in 1998, Windows Script Host (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) and console-based mode (with the cscript.exe host). They have been a part of Windows since Windows 98.
- .ps1: In 2006, Microsoft released a further raw-text script processor, Windows PowerShell, which can be used with Windows XP (SP2/SP3) and above. This is designed for both interactive use from a command line interface, and also for writing scripts, and has a strong resemblance to Unix shells.[6]
In addition to these, powerful cross-platform scripting tools such as Perl, Python, Ruby and Rexx are now available for Windows.
If the appropriate extension is set in the PATHEXT environment, the file will run without need of typing in the 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
- ^ http://www.winsupersite.com/showcase/win2008_cli.asp
- ^ http://geekswithblogs.net/sdorman/archive/2006/06/18/82258.aspx