Javascript required
Skip to content Skip to sidebar Skip to footer

Batch File Read Line From Text File

Script file for Microsoft computer operating systems

Batch file
Batch file icon.png
Filename extensions .bat, .cmd, .btm
Cyberspace media type
  • application/bat
  • application/ten-bat
  • awarding/x-msdos-plan
  • text/plainly
Blazon of format Scripting
Container for Scripts

A batch file is a script file in DOS, OS/two and Microsoft Windows. It consists of a series of commands to be executed by the command-line interpreter, stored in a obviously text file. A batch file may comprise any control the interpreter accepts interactively and apply constructs that enable conditional branching and looping within the batch file, such as IF, FOR, and GOTO labels. The term "batch" is from batch processing, pregnant "non-interactive execution", though a batch file might not process a batch of multiple data.

Similar to Job Command 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 prepare up a script to automate them. When a batch file is run, the vanquish plan (usually COMMAND.COM or cmd.exe) reads the file and executes its commands, unremarkably line-past-line.[1] Unix-like operating systems, such as Linux, accept a similar, but more flexible, type of file called a beat script.[two]

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, due east.chiliad., .btm in 4DOS, 4OS2 and 4NT related shells.

The detailed handling of batch files has inverse significantly between versions. Some of the particular in this article applies to all batch files, while other details apply but to certain versions.

Variants [edit]

DOS [edit]

In DOS, a batch file can be started from the control-line interface by typing its proper name, followed by any required parameters and pressing the ↵ Enter primal. When DOS loads, the file AUTOEXEC.BAT, when present, is automatically executed, so whatsoever commands that demand to be run to set up up the DOS environment may be placed in this file. Computer users would have the AUTOEXEC.BAT file prepare the organization date and time, initialize the DOS environment, load whatsoever resident programs or device drivers, or initialize network connections and assignments.

A .bat file proper name extension identifies a file containing commands that are executed by the command interpreter Command.COM line by line, as if it were a listing of commands entered manually, with some extra batch-file-specific commands for basic programming functionality, including a GOTO command for irresolute menses of line execution.

Early Windows [edit]

Microsoft 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 gild to start it, the WIN command was used, which could exist added to the cease 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 3.1x and earlier, as well as Windows 9x invoked COMMAND.COM to run batch files.

OS/2 [edit]

The IBM Os/ii operating organisation supported DOS-style batch files. Information technology too included a version of REXX, a more than avant-garde batch-file scripting language. IBM and Microsoft started developing this system, only during the construction of it broke upwardly after a dispute; equally a issue of this, IBM referred to their DOS-like console shell without mention of Microsoft, naming it but DOS, although this seemingly fabricated no deviation with regard to the mode batch files worked from Control.COM.

Bone/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 information file. The named program tin be a script file; this is similar to the #! mechanism.

Windows NT [edit]

Different Windows 98 and earlier, the Windows NT family of operating systems does not depend on MS-DOS. Windows NT introduced an enhanced 32-fleck control 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, and so that the aforementioned batch file (with different extension) might piece of work differently with cmd.exe and COMMAND.COM. In about cases, performance is identical if the few unsupported commands are not used. Cmd.exe'due south 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-way batch files.

As of Windows 8[update], cmd.exe is the normal command interpreter for batch files; the older Control.COM can exist run as well in 32-scrap versions of Windows able to run 16-bit programs.[nb 1]

Filename extensions [edit]

.bat
The first filename extension used past Microsoft for batch files. This extension runs with DOS and all versions of Windows, under Control.COM or cmd.exe, despite the different means 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 file name extension, so cmd.exe scripts are not executed in the wrong Windows environment by error. In improver, append, dpath, ftype, prepare, path, assoc and prompt commands, when executed from a .bat file, change the value of the errorlevel variable only upon an fault, whereas from inside a .cmd file, they would affect errorlevel fifty-fifty when returning without an error.[three] It is too used by IBM'due south Os/2 for batch files.
.btm
The extension used by 4DOS, 4OS2, 4NT and Take Command. These scripts are faster, specially with longer ones, as the script is loaded entirely ready for execution, rather than line-past-line.[4]

Batch file parameters [edit]

Command.COM and cmd.exe support special variables (%0, %ane through %nine) in lodge to refer to the path and proper name of the batch job and the starting time ix calling parameters from inside the batch job, see also SHIFT. Not-existent parameters are replaced by a zero-length string. They tin can be used like to surroundings variables, but are not stored in the environment. Microsoft and IBM refer to these variables as replacement parameters or replaceable parameters, whereas Digital Research, Novell and Caldera established the term replacement variables [5] for them. JP Software calls them batch file parameters.[6]

Examples [edit]

This example batch file displays How-do-you-do World!, prompts and waits for the user to press a primal, and and then terminates. (Note: Information technology does not matter if commands are lowercase or uppercase unless working with variables)

                        @            ECHO            OFF            ECHO            Hello Globe!            Interruption          

To execute the file, it must be saved with the filename extension suffix .bat (or .cmd for Windows NT-type operating systems) in apparently 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 proceed . . .        

Explanation [edit]

The interpreter executes each line in plow, starting with the first. The @ symbol at the start of whatsoever line prevents the prompt from displaying that control as it is executed. The command ECHO OFF turns off the prompt permanently, or until it is turned on once again. The combined @Repeat OFF is frequently as here the first line of a batch file, preventing any commands from displaying, itself included. Then the next line is executed and the ECHO Hello Earth! command outputs Hello World!. The next line is executed and the Interruption command displays Press any primal to keep . . . and pauses the script'due south execution. After a primal is pressed, the script terminates, as there are no more than commands. In Windows, if the script is executed from an already running control prompt window, the window remains open at the prompt as in MS-DOS; otherwise, the window closes on termination.

Limitations and exceptions [edit]

Cypher values in variables [edit]

Variable expansions are substituted textually into the command, and thus variables which contain aught simply disappear from the syntax, and variables which contain spaces turn into multiple tokens. This can lead to syntax errors or bugs.

For case, if %foo% is empty, this statement:

parses as the erroneous construct:

Similarly, if %foo% contains abc def, and so a unlike syntax error results:

                        IF            abc              def            ==bar            Echo            Equal          

The usual style to foreclose this trouble is to surroundings variable expansions in quotes and then that an empty variable expands into the valid expression IF ""=="bar" instead of the invalid IF ==bar. The text that is beingness 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 and later on may be used to avoid these syntactical errors. In this case, null or multi-word variables do not neglect syntactically because the value is expanded after the IF command is parsed:

Some other deviation in Windows 2000 or higher is that an empty variable (undefined) is not substituted. Equally 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 divers)            else            (            repeat            MyVar is            %MyVar%            )            MyVar is %MyVar%          

Batch interpreters prior to Windows 2000 would have displayed upshot MyVar is not defined.

Quotation marks and spaces in passed strings [edit]

Unlike Unix/POSIX processes, which receive their command-line arguments already carve up upwardly past the trounce into an assortment of strings, a Windows procedure receives the entire command-line as a unmarried string, via the GetCommandLine API role. As a result, each Windows awarding tin can implement its ain parser to split the entire control line into arguments. Many applications and command-line tools have evolved their own syntax for doing that, and so at that place is no single convention for quoting or escaping metacharacters on Windows command lines.

  • For some commands, spaces are treated as delimiters that separate arguments, unless those spaces are enclosed by quotation marks. Various conventions be of how quotation marks can be passed on to the awarding:
    • A widely used convention is implemented past the command-line parser built into the Microsoft Visual C++ runtime library in the CommandLineToArgvW part. Information technology uses the convention that 2northward backslashes followed by a quotation mark (") produce n backslashes followed past a begin/finish quote, whereas (iin)+ane backslashes followed by a quotation mark again produce north backslashes followed by a quotation marking literal. The same convention is role of the .Cyberspace Framework specification.[7]
      • An undocumented aspect is that "" occurring in the middle of a quoted string produces a single quotation mark.[7] (A CRT modify in 2008 [msvcr90] modified this undocumented handling of quotes.[8]) This is helpful for inserting a quotation mark in an argument without re-enabling interpretation of cmd metacharacters like |, & and >. (cmd does non recognize the usual \" as escaping the quote. It re-enables these special meanings on seeing the quote, thinking the quotation has ended.)
    • Some other convention is that a single quotation mark (") is non included as office of the cord. However, an escaped quotation mark (""") tin can be function of the string.[ citation needed ]
    • Notwithstanding some other common convention comes from the use of Cygwin-derived ported programs. It does not differentiate between backslashes occurring earlier or not earlier quotes. Meet glob (programming) § Windows and DOS for information on these culling command-line parsers.[ix]
    • Some important Windows commands, similar cmd.exe and wscript.exe, use their own rules.[8]
  • For other commands, spaces are not treated as delimiters and therefore exercise not need quotation marks. If quotes are included they become role of the string. This applies to some built-in commands like repeat.

Where a string contains quotation marks, and is to be inserted into another line of text that must too be enclosed in quotation marks, particular attention to the quoting mechanism is required:

                        C:\>            gear up            foo            =            "this string is enclosed in quotation marks"            C:\>            echo            "exam ane                        %foo%            "            "test 1 "this cord is enclosed in quotation marks""            C:\>eventcreate /T Warning /ID 1 /L Organization /SO            "Source"            /D            "Case:                        %foo%            "            ERROR: Invalid Argument/Option - 'cord'.            Blazon "EVENTCREATE /?" for usage.          

On Windows 2000 and later, the solution is to replace each occurrence of a quote character within a value past a series of 3 quote characters:

                        C:\>            set            foo            =            "this string is enclosed in quotes"            C:\>            set            foo            =            %foo:"="""%            C:\>            echo            "test i                        %foo%            "            "test 1 """this string is enclosed in quotes""""            C:\>eventcreate /T Warning /ID one /L Arrangement /SO            "Source"            /D            "Example:                        %foo%            "            SUCCESS: A 'Warning' type event is created in the 'Source' log/source.          

Escaped characters in strings [edit]

Some characters, such every bit pipe (|) characters, have special significant to the command line. They cannot be printed equally text using the ECHO command unless escaped using the caret ^ symbol:

                        C:\>            Echo            foo            |            bar            'bar' is non recognized every bit an internal or external control,            operable programme or batch file.            C:\>            Echo            foo            ^|            bar            foo | bar          

However, escaping does non work as expected when inserting the escaped character into an environment variable. The variable ends upward containing a live pipe command when merely echoed. It is necessary to escape both the caret itself and the escaped graphic symbol for the character brandish as text in the variable:

                        C:\>            prepare            foo            =bar            |            baz            'baz' is not recognized equally an internal or external command,            operable program or batch file.            C:\>            set            foo            =bar            ^|            baz            C:\>            echo            %foo%            'baz' is not recognized every bit an internal or external command,            operable plan or batch file.            C:\>            set            foo            =bar            ^^^|            baz            C:\>            echo            %foo%            bar | baz          

The delayed !VARIABLE! expansion bachelor with CMD /V:ON or with SETLOCAL ENABLEDELAYEDEXPANSION in Windows 2000 and afterward may be used to bear witness special characters stored in environment variables considering the variable value is expanded after the command was parsed:

                        C:\>cmd /Five:ON            Microsoft Windows [Version 6.ane.7601]            Copyright (c) 2009 Microsoft Corporation. All rights reserved.            C:\>            ready            foo            =bar            ^|            baz            C:\>            echo            !foo!            bar | baz          

Sleep or scripted delay [edit]

Until the TIMEOUT command was introduced with Windows Vista, there was no easy way to implement a timed pause, as the Break command halts script activity indefinitely until any key is pressed.

Many workarounds were possible,[10] simply generally only worked in some environments: The CHOICE command was not bachelor in older DOS versions, PING was only available if TCP/IP was installed, and so on. No solution was available from Microsoft, but a number of small-scale utility programs, could be installed from other sources. A commercial example would be the 1988 Norton Utilities Batch Enhancer (Be) command, where BE Filibuster xviii would wait for 1 second, or the free 94-byte Expect.COM[11] where WAIT 5 would await for v seconds, and then return control to the script. Most such programs are 16-bit .COM files, so are incompatible with 64-bit Windows.

Text output with stripped CR/LF [edit]

Usually, all printed text automatically has the command characters for carriage return (CR) and line feed (LF) appended to the end of each line.

  • batchtest.bat
                                            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 interruption the output onto separate lines:

                        C:\>            @            repeat            Bulletin 1&@            echo            Message two            Message 1            Message 2          

A pull a fast one on discovered with Windows 2000 and later on 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, only does follow Line 2 and Line 3:

  • batchtest2.bat
                                            @                    echo                    off                    set                    /p                    =                    "Message one"                    <nul                    echo                    Message 2                    echo                    Bulletin 3                  
                                            C:\>batchtest2.bat                    Bulletin 1Message 2                    Bulletin iii                  

This can exist used to output information to a text file without CR/LF appended to the end:

                        C:\>            set up            /p            =            "Message one"            <nul            >data.txt            C:\>            set up            /p            =            "Message 2"            <nul            >>data.txt            C:\>            set            /p            =            "Message three"            <nul            >>information.txt            C:\>            type            data.txt            Message 1Message 2Message three          

Even so, there is no mode to inject this stripped CR/LF prompt output directly into an environment variable.

Setting a Compatible Naming Convention (UNC) working directory from a shortcut [edit]

It is not possible to accept a command prompt that uses a UNC path as the current working directory; eastward.g. \\server\share\directory\

The command prompt requires the use of drive messages to assign a working directory, which makes running complex batch files stored on a server UNC share more hard. While a batch file can exist run from a UNC file path, the working directory default is C:\Windows\System32\.

In Windows 2000 and later, a workaround is to use the PUSHD and POPD control with command extensions.[nb 2]

If not enabled by default, command extensions tin be temporarily enabled using the /E:ON switch for the control interpreter.

So to run a batch file on a UNC share, assign a temporary drive alphabetic character to the UNC share, and utilize the UNC share as the working directory of the batch file, a Windows shortcut tin can be constructed that looks like this:

  • Target: %COMSPEC% /East:ON /C "PUSHD """\\SERVER\SHARE\DIR1\DIR2\""" & BATCHFILE.BAT & POPD"

The working directory attribute of this shortcut is ignored.

This also solves a trouble related to User Account Control (UAC) on Windows Vista and newer. When an administrator is logged on and UAC is enabled, and they endeavour to run a batch file every bit administrator from a network drive letter of the alphabet, using the right-click file context menu, the operation will unexpectedly neglect. This is because the elevated UAC privileged account context does not have network drive letter assignments, and information technology is not possible to assign drive messages for the elevated context via the Explorer vanquish or logon scripts. Withal, past creating a shortcut to the batch file using the above PUSHD / POPD construct, and using the shortcut to run the batch file as administrator, the temporary drive letter will be created and removed in the elevated account context, and the batch file will function correctly.

The post-obit syntax does correctly aggrandize to the path of the current batch script.

%~dp0        

UNC default paths are turned off by default as they used to crash older programs.[12]

The Dword registry value DisableUNCCheck at HKEY_CURRENT_USER\Software\Microsoft\Command Processor [12] allows the default directory to be UNC. CD command will decline to change but placing a UNC path in Default Directory in a shortcut to Cmd or by using the Start command. starting time "" /d \\127.0.0.1\C$ "cmd /k" (C$ share is for administrators).

Character prepare [edit]

Batch files utilize an OEM character set, as divers past the computer, e.yard. Code folio 437. The not-ASCII parts of these are incompatible with the Unicode or Windows character sets otherwise used in Windows so care needs to be taken.[xiii] Non-English file names work only if entered through a DOS character set compatible editor. File names with characters outside this prepare exercise not work in batch files.

To go output in Unicode into file pipes from an internal command such as dir, ane can use the cmd /U command. For case, cmd /U /C dir > files.txt creates a file containing a directory list with correct Windows characters, in the UTF-16LE encoding.

Batch viruses and malware [edit]

As with any other programming language, batch files tin can be used maliciously. Simple trojans and fork bombs are easily created, and batch files can practise a grade 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 adequacy.[14]

The following command in a batch file will delete all the data in the current directory (folder) - without get-go asking for confirmation:

These three commands are a simple fork bomb that volition continually replicate itself to deplete available system resource, slowing down or crashing the system:

                        :            TOP            commencement            ""            %0            goto            Elevation          

Other Windows scripting languages [edit]

The cmd.exe command processor that interprets .cmd files is supported in all 32- and 64-bit versions of Windows upwards to at least Windows x[update]. Command.EXE, which interprets .BAT files, was supported in all 16- and 32-fleck versions upward to at to the lowest degree Windows 10.[nb 3]

There are other, afterwards and more powerful, scripting languages available for Windows. However, these require the scripting language interpreter to be installed earlier they can exist used:

  • KiXtart (.kix) — developed past a Microsoft employee in 1991, specifically to encounter the need for commands useful in a network logon script while retaining the elementary 'feel' of a .cmd file.
  • Windows Script Host (.vbs , .js and .wsf) — released by Microsoft in 1998, and consisting of cscript.exe and wscript.exe, runs scripts written in VBScript or JScript. Information technology 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.
  • PowerShell (.ps1) — released in 2006 by Microsoft and can operate with Windows XP (SP2/SP3) and subsequently versions. PowerShell can operate both interactively (from a command-line interface) and also via saved scripts, and has a strong resemblance to Unix shells.[xv]
  • Unix-style shell scripting languages can be used if a Unix compatibility tool, such every bit Cygwin, is installed.
  • Cross-platform scripting tools including Perl, Python, Ruby, Rexx, Node.js and PHP are available for Windows.

Script files run if the filename without extension is entered. There are rules of precedence governing estimation of, say, DoThis if DoThis.com, DoThis.exe, DoThis.bat, DoThis.cmd, etc. exist; past default DoThis.com has highest priority. This default order may exist modified in newer operating systems by the user-settable PATHEXT environment variable.

See likewise [edit]

  • Listing of DOS commands

Notes [edit]

  1. ^ To verify that Control.COM remains bachelor (in the \WINDOWS\SYSTEM32 directory), type Control.COM at the 32-bit Windows vii command prompt.
  2. ^ "If Command Extensions are enabled the PUSHD command accepts network paths in improver to the normal drive letter of the alphabet and path. If a network path is specified, PUSHD creates a temporary drive letter that points to that specified network resources and then change the electric current drive and directory, using the newly defined bulldoze alphabetic character. Temporary bulldoze messages are allocated from Z: on down, using the first unused drive letter establish." --The assistance for PUSHD in Windows 7
  3. ^ Availability of CMD.EXE and COMMAND.COM can be confirmed by invoking them in any version of Windows (Control.COM not in 64-chip versions; probably only available in Windows viii 32-bit versions if installed with selection to support 16-fleck programs).

References [edit]

  1. ^ "Using batch files: Scripting; Management Services". Technet.microsoft.com. 2005-01-21. Retrieved 2012-11-xxx .
  2. ^ Henry-Stocker, Sandra (2007-07-eighteen). "Use your Unix scripting skills to write a batch file". itworld.com. It Earth. Retrieved 2018-06-13 .
  3. ^ "Difference betwixt bat and cmd | WWoIT - Wayne'due south Earth of IT". waynes-world-it.blogspot.fr. 2012-eleven-xv. Retrieved 2012-xi-30 .
  4. ^ "btm file extension :: all nigh the .btm file type". Cryer.co.britain. Retrieved 2012-11-thirty .
  5. ^ Caldera DR-DOS vii.02 User Guide, Caldera, Inc., 1998 [1993, 1997], archived from the original on 2016-11-05, retrieved 2013-08-10
  6. ^ Brothers, Hardin; Rawson, Tom; Conn, Rex C.; Paul, Matthias R.; Dye, Charles E.; Georgiev, Luchezar I. (2002-02-27). 4DOS 8.00 online assistance.
  7. ^ a b ".Internet Cadre Runtime: System.Diagnostics.Process.Unix". GitHub . Retrieved 2020-02-11 . Two consecutive double quotes inside an inQuotes region should result in a literal double quote (the parser is left in the inQuotes region). This beliefs is non office of the spec of code:ParseArgumentsIntoList, but is compatible with CRT and .NET Framework.
  8. ^ a b Deley, David. "How Command Line Parameters Are Parsed".
  9. ^ "Kid process documentation, section Windows Command Line, NodeJS PR #29576". GitHub . Retrieved 2020-02-eleven .
  10. ^ "How to do a filibuster", ericphelps.com
  11. ^ Utilities for DOS, linking to Wait.ZIP (archive of Await.COM) and other programs
  12. ^ a b https://back up.microsoft.com/en-us/kb/156276 [ dead link ]
  13. ^ Chen, Raymond. "Keep your heart on the code folio". Microsoft.
  14. ^ http://world wide web.explorehacking.com/2011/01/batch-files-art-of-creating-viruses.html
  15. ^ "Windows PowerShell - Unix comes to Windows". Geekswithblogs.net. Retrieved 2012-11-30 .

External links [edit]

  • Microsoft Windows XP Batch file reference
  • How Windows batch files piece of work
  • Windows x batch file commands
  • FreeDOS' FreeCOM : consummate feature list
  • Windows Command Line Interface script programming links
  • scripting related information (also command line)
  • dbenham. "How does the Windows Control Interpreter (CMD.EXE) parse scripts?". Stack Overflow.

seewatich35.blogspot.com

Source: https://en.wikipedia.org/wiki/Batch_file