Batch file
A batch file is a script file in DOS, OS/2 and Microsoft Windows. It consists of a series of commands to be executed by the command-line interpreter, stored in a plain text file. A batch file may contain any command the interpreter accepts interactively and use constructs that enable conditional branching and looping within the batch file, such as Similar to Job Control Language (JCL), DCL 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, but more flexible, type of file called a shell script.[2] The filename extension .bat is used in DOS and Windows. Windows NT and OS/2 also added .cmd. Batch files for other environments may have different extensions, e.g., .btm in 4DOS, 4OS2 and 4NT related shells. The detailed handling of batch files has changed significantly between versions. Some of the detail in this article applies to all batch files, while other details apply only to certain versions. VariantsDOSIn MS-DOS, a batch file can be started from the command-line interface by typing its name, followed by any required parameters and pressing the ↵ Enter key. When DOS loads, the file AUTOEXEC.BAT, when present, is automatically executed, so any commands that need to be run to set up the DOS environment may be placed in this file. Computer users would have the AUTOEXEC.BAT file set up the system date and time, initialize the DOS environment, load any resident programs or device drivers, or initialize network connections and assignments. A .bat file name extension identifies a file containing commands that are executed by the command interpreter COMMAND.COM line by line, as if it were a list of commands entered manually, with some extra batch-file-specific commands for basic programming functionality, including a Early WindowsMicrosoft Windows was introduced in 1985 as a graphical user interface-based (GUI) overlay on text-based operating systems and was designed to run on DOS. In order to start it, the OS/2The IBM OS/2 operating system supported DOS-style batch files. It also included a version of REXX, 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 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 used by Unix-like operating systems. Windows NTUnlike Windows 98 and earlier, the Windows NT family of operating systems does not depend on MS-DOS. Windows NT introduced an enhanced 32-bit command interpreter (cmd.exe) that 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 (with different extension) 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[update], cmd.exe is the normal command interpreter for batch files; the older COMMAND.COM can be run as well in 32-bit versions of Windows able to run 16-bit programs.[nb 1] [3]==Filename extensions==
Batch file parametersCOMMAND.COM and cmd.exe support special variables ( ExamplesThis example batch file displays @ECHO OFF
ECHO Hello World!
PAUSE
To execute the file, it must be saved with the filename extension suffix .bat (or .cmd for Windows NT-type operating systems) in plain text format, typically created by using a text editor such as Microsoft Notepad or a word processor working in plain text mode. When executed, the following is displayed: Hello World! Press any key to continue . . . ExplanationThe interpreter executes each line in turn, starting with the first. The Limitations and exceptionsNull values in variablesVariable 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: IF %foo%==bar ECHO Equal
parses as the erroneous construct: IF ==bar ECHO Equal
Similarly, if IF abc def==bar ECHO Equal
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 "%foo%"=="bar" ECHO Equal
The delayed !VARIABLE! expansion available in Windows 2000 and later may be used to avoid these syntactical errors. In this case, null or multi-word variables do not fail syntactically because the value is expanded after the IF command is parsed: IF !foo!==bar ECHO Equal
Another difference in Windows 2000 or higher is that an empty variable (undefined) is not substituted. As described in previous examples, previous batch interpreter behaviour would have resulted in an empty string. Example: C:\>set MyVar=
C:\>echo %MyVar%
%MyVar%
C:\>if "%MyVar%"=="" (echo MyVar is not defined) else (echo MyVar is %MyVar%)
MyVar is %MyVar%
Batch interpreters prior to Windows 2000 would have displayed result Quotation marks and spaces in passed stringsUnlike Unix/POSIX processes, which receive their command-line arguments already split up by the shell into an array of strings, a Windows process receives the entire command-line as a single string, via the GetCommandLine API function. As a result, each Windows application can implement its own parser to split the entire command line into arguments. Many applications and command-line tools have evolved their own syntax for doing that, and so there is no single convention for quoting or escaping metacharacters on Windows command lines.
Where a string contains quotation marks, and is to be inserted into another line of text that must also be enclosed in quotation marks, particular attention to the quoting mechanism is required: 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.
On Windows 2000 and later, the solution is to replace each occurrence of a quote character within a value by a series of three quote characters: 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 stringsSome characters, such as pipe ( 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. 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 expansion available with or with in Windows 2000 and later may be used to show special characters stored in environment variables because the variable value is expanded after the command was parsed: C:\>cmd /V:ON
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
C:\>set foo=bar ^| baz
C:\>echo !foo!
bar | baz
Sleep or scripted delayUntil the TIMEOUT command was introduced with Windows Vista, there was no easy way to implement a timed pause, as the PAUSE command halts script activity indefinitely until any key is pressed. Many workarounds were possible,[11] but generally only worked in some environments: The Text output with stripped CR/LFNormally, all printed text automatically has the control characters for carriage return (CR) and line feed (LF) 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: C:\>@echo Message 1&@echo Message 2
Message 1
Message 2
A trick discovered with Windows 2000 and later 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 Message 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: C:\>set /p ="Message 1"<nul >data.txt
C:\>set /p ="Message 2"<nul >>data.txt
C:\>set /p ="Message 3"<nul >>data.txt
C:\>type data.txt
Message 1Message 2Message 3
However, there is no way to inject this stripped CR/LF prompt output directly into an environment variable. Setting a Uniform Naming Convention (UNC) working directory from a shortcutIt is not possible to have a command prompt that uses a UNC path as the current working directory; e.g. 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 default is In Windows 2000 and later, a workaround is to use the If not enabled by default, command extensions can be temporarily enabled using the 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. This also solves a problem related to User Account Control (UAC) on Windows Vista and newer. When an administrator is logged on and UAC is enabled, and they try to run a batch file as administrator from a network drive letter, using the right-click file context menu, the operation will unexpectedly fail. This is because the elevated UAC privileged account context does not have network drive letter assignments, and it is not possible to assign drive letters for the elevated context via the Explorer shell or logon scripts. However, by creating a shortcut to the batch file using the above The following syntax does correctly expand to the path of the current batch script. %~dp0 UNC default paths are turned off by default as they used to crash older programs.[13] The Dword registry value Character setBatch files use an OEM 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.[14] Non-English file names work only if entered through a DOS character set compatible editor. File names with characters outside this set do not work in batch files. To get a command prompt with Unicode instead of Code page 437 or similar, one can use the Batch viruses and malwareAs with any other programming language, batch files can be used maliciously. Simple trojans and fork bombs are easily created, and batch files can do a form of DNS poisoning by modifying the hosts file. Batch viruses are possible, and can also spread themselves via USB flash drives by using Windows' Autorun capability.[15] The following command in a batch file will delete all the data in the current directory (folder) - without first asking for confirmation: del /Q *.*
These three commands are a simple fork bomb that will continually replicate itself to deplete available system resources, slowing down or crashing the system: :TOP
start "" %0
goto TOP
Other Windows scripting languagesThe cmd.exe command processor that interprets .cmd files is supported in all 32 bit versions of Windows up to Windows 10 and 64-bit versions Windows of up to Windows 11. COMMAND.EXE, which interprets .BAT files, was supported in all 16-bit and 32-bit versions up to at least Windows 10.[nb 3] 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:
Script files run if the filename without extension is entered. There are rules of precedence governing interpretation of, say, See also
Notes
References
External linksWikibooks has a book on the topic of: Guide to Windows commands |