Dos Script to Read File Line by Line
Filename extensions | .bat , .cmd , .btm |
---|---|
Internet media type |
|
Type of format | Scripting |
Container for | Scripts |
A batch file is a script file in DOS, OS/two and Microsoft Windows. It consists of a serial of commands to be executed by the command-line interpreter, stored in a plain text file. A batch file may comprise any command the interpreter accepts interactively and utilize constructs that enable provisional branching and looping within the batch file, such as IF
, FOR
, and GOTO
labels. The term "batch" is from batch processing, meaning "non-interactive execution", though a batch file might non process a batch of multiple data.
Similar to Chore 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 past allowing the user to set upward a script to automate them. When a batch file is run, the vanquish program (usually COMMAND.COM or cmd.exe) reads the file and executes its commands, unremarkably line-past-line.[i] Unix-similar operating systems, such as Linux, take a like, but more flexible, blazon of file chosen a beat script.[ii]
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 unlike extensions, eastward.g., .btm in 4DOS, 4OS2 and 4NT related shells.
The detailed handling of batch files has changed significantly between versions. Some of the item in this article applies to all batch files, while other details apply only to sure versions.
Variants [edit]
DOS [edit]
In DOS, a batch file can be started from the command-line interface by typing its name, followed by whatsoever required parameters and pressing the ↵ Enter central. When DOS loads, the file AUTOEXEC.BAT, when present, is automatically executed, so whatever commands that demand to be run to set the DOS environs may exist placed in this file. Computer users would accept the AUTOEXEC.BAT file ready the system date and time, initialize the DOS surroundings, 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, every bit if it were a list of commands entered manually, with some actress batch-file-specific commands for basic programming functionality, including a GOTO
command for changing flow of line execution.
Early on 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 society to start it, the WIN
command was used, which could be added to the end of the AUTOEXEC.BAT file to allow automatic loading of Windows. In the before versions, i could run a .bat type file from Windows in the MS-DOS Prompt. Windows 3.1x and earlier, as well every bit Windows 9x invoked Command.COM to run batch files.
Bone/ii [edit]
The IBM Os/ii operating arrangement supported DOS-style batch files. Information technology also included a version of REXX, a more advanced batch-file scripting linguistic communication. IBM and Microsoft started developing this system, but during the construction of it bankrupt upward after a dispute; equally a consequence of this, IBM referred to their DOS-similar panel vanquish without mention of Microsoft, naming it but DOS, although this seemingly made no difference with regard to the style batch files worked from COMMAND.COM.
Os/2's batch file interpreter besides supports an EXTPROC command. This passes the batch file to the programme named on the EXTPROC file as a data file. The named programme can be a script file; this is similar to the #! mechanism.
Windows NT [edit]
Unlike Windows 98 and before, the Windows NT family of operating systems does not depend on MS-DOS. Windows NT introduced an enhanced 32-scrap 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 dissimilar way, and then that the aforementioned batch file (with unlike extension) might work differently with cmd.exe and COMMAND.COM. In nearly cases, functioning is identical if the few unsupported commands are non used. Cmd.exe's extensions to Control.COM tin 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-mode batch files.
Every bit of Windows 8[update], cmd.exe is the normal command interpreter for batch files; the older COMMAND.COM can be run besides in 32-bit versions of Windows able to run 16-bit programs.[nb 1]
Filename extensions [edit]
- .bat
- The offset filename extension used by Microsoft for batch files. This extension runs with 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 estimation. COMMAND.COM does not recognize this file proper noun extension, and then cmd.exe scripts are not executed in the wrong Windows environment by mistake. In addition,
append
,dpath
,ftype
,fix
,path
,assoc
andprompt
commands, when executed from a .bat file, alter the value of theerrorlevel
variable only upon an error, whereas from within a .cmd file, they would bear upon errorlevel fifty-fifty when returning without an error.[three] It is as well used by IBM's OS/2 for batch files. - .btm
- The extension used by 4DOS, 4OS2, 4NT and Take Command. These scripts are faster, especially with longer ones, equally the script is loaded entirely ready for execution, rather than line-by-line.[4]
Batch file parameters [edit]
Control.COM and cmd.exe back up special variables (%0
, %1
through %9
) in club to refer to the path and name of the batch job and the beginning nine calling parameters from within the batch task, see as well SHIFT. Non-real parameters are replaced by a zero-length string. They can be used similar 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 Inquiry, Novell and Caldera established the term replacement variables [v] for them. JP Software calls them batch file parameters.[6]
Examples [edit]
This example batch file displays Hello Globe!
, prompts and waits for the user to printing a key, and and then terminates. (Note: Information technology does not thing if commands are lowercase or uppercase unless working with variables)
@ Repeat OFF Repeat Hello World! Intermission
To execute the file, information technology must be saved with the filename extension suffix .bat (or .cmd for Windows NT-type operating systems) in patently text format, typically created by using a text editor such every bit Microsoft Notepad or a word processor working in plain text mode.
When executed, the following is displayed:
Hello World! Press any key to go on . . .
Explanation [edit]
The interpreter executes each line in turn, starting with the get-go. The @
symbol at the outset of any line prevents the prompt from displaying that command as it is executed. The command ECHO OFF
turns off the prompt permanently, or until it is turned on again. The combined @ECHO OFF
is oftentimes as here the beginning line of a batch file, preventing any commands from displaying, itself included. Then the next line is executed and the ECHO Hi Earth!
command outputs Howdy World!
. The next line is executed and the Suspension
control displays Press whatsoever key to continue . . .
and pauses the script's execution. After a key is pressed, the script terminates, every bit there are no more commands. In Windows, if the script is executed from an already running command prompt window, the window remains open at the prompt equally in MS-DOS; otherwise, the window closes on termination.
Limitations and exceptions [edit]
Zippo values in variables [edit]
Variable expansions are substituted textually into the command, and thus variables which contain nada but disappear from the syntax, and variables which comprise spaces plow into multiple tokens. This tin pb 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 mistake results:
IF abc def ==bar ECHO Equal
The usual way to prevent this trouble is to surround variable expansions in quotes then that an empty variable expands into the valid expression IF ""=="bar"
instead of the invalid IF ==bar
. The text that is existence compared to the variable must likewise be enclosed in quotes, considering 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 may be used to avoid these syntactical errors. In this case, nothing or multi-discussion variables do not fail syntactically because the value is expanded afterwards the IF command is parsed:
Another departure in Windows 2000 or higher is that an empty variable (undefined) is non substituted. Every bit described in previous examples, previous batch interpreter behaviour would have resulted in an empty string. Example:
C:\> fix MyVar = C:\> echo %MyVar% %MyVar% C:\> if " %MyVar% " == "" ( repeat MyVar is not defined) else ( echo MyVar is %MyVar% ) MyVar is %MyVar%
Batch interpreters prior to Windows 2000 would take displayed outcome MyVar is not defined
.
Quotation marks and spaces in passed strings [edit]
Unlike Unix/POSIX processes, which receive their command-line arguments already split up past the vanquish into an array of strings, a Windows process receives the entire command-line as a single string, via the GetCommandLine API function. As a issue, each Windows application tin implement its own parser to split the entire command line into arguments. Many applications and command-line tools take evolved their own syntax for doing that, and so there is no unmarried convention for quoting or escaping metacharacters on Windows command lines.
- For some commands, spaces are treated as delimiters that split up arguments, unless those spaces are enclosed by quotation marks. Various conventions exist of how quotation marks can exist passed on to the application:
- A widely used convention is implemented by the command-line parser built into the Microsoft Visual C++ runtime library in the CommandLineToArgvW office. It uses the convention that iin backslashes followed by a quotation marker (") produce n backslashes followed by a brainstorm/end quote, whereas (iinorth)+1 backslashes followed by a quotation marker over again produce n backslashes followed by a quotation mark literal. The same convention is part of the .Cyberspace Framework specification.[7]
- An undocumented attribute is that "" occurring in the middle of a quoted cord produces a single quotation mark.[7] (A CRT alter in 2008 [msvcr90] modified this undocumented treatment of quotes.[8]) This is helpful for inserting a quotation mark in an argument without re-enabling estimation of cmd metacharacters like |, & and >. (cmd does not recognize the usual \" equally escaping the quote. It re-enables these special meanings on seeing the quote, thinking the quotation has ended.)
- Another convention is that a single quotation mark (") is not included as part of the string. However, an escaped quotation mark (""") can exist part of the string.[ commendation needed ]
- Yet another common convention comes from the employ of Cygwin-derived ported programs. It does non differentiate betwixt backslashes occurring before or not before quotes. Meet glob (programming) § Windows and DOS for information on these alternative command-line parsers.[nine]
- Some important Windows commands, like
cmd.exe
andwscript.exe
, utilize their ain rules.[8]
- A widely used convention is implemented by the command-line parser built into the Microsoft Visual C++ runtime library in the CommandLineToArgvW office. It uses the convention that iin backslashes followed by a quotation marker (") produce n backslashes followed by a brainstorm/end quote, whereas (iinorth)+1 backslashes followed by a quotation marker over again produce n backslashes followed by a quotation mark literal. The same convention is part of the .Cyberspace Framework specification.[7]
- For other commands, spaces are non treated as delimiters and therefore do non demand quotation marks. If quotes are included they become part of the string. This applies to some built-in commands like echo.
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:\> repeat "test 1 %foo% " "test i "this string is enclosed in quotation marks"" C:\>eventcreate /T Warning /ID 1 /L System /SO "Source" /D "Case: %foo% " Mistake: Invalid Statement/Option - 'string'. Type "EVENTCREATE /?" for usage.
On Windows 2000 and later, the solution is to replace each occurrence of a quote grapheme within a value by a series of three quote characters:
C:\> set foo = "this string is enclosed in quotes" C:\> set foo = %foo:"="""% C:\> repeat "test 1 %foo% " "test 1 """this cord is enclosed in quotes"""" C:\>eventcreate /T Alert /ID 1 /L Organization /And then "Source" /D "Example: %foo% " SUCCESS: A 'Warning' type consequence is created in the 'Source' log/source.
Escaped characters in strings [edit]
Some characters, such as pipe (|
) characters, have special meaning to the command line. They cannot be printed every bit text using the ECHO command unless escaped using the caret ^ symbol:
C:\> Repeat foo | bar 'bar' is not recognized as an internal or external control, operable programme or batch file. C:\> Echo foo ^| bar foo | bar
All the same, escaping does not work as expected when inserting the escaped graphic symbol into an environs variable. The variable ends upwards containing a live pipage command when merely echoed. It is necessary to escape both the caret itself and the escaped grapheme for the grapheme display equally text in the variable:
C:\> set foo =bar | baz 'baz' is non recognized as an internal or external control, operable program or batch file. C:\> set foo =bar ^| baz C:\> repeat %foo% 'baz' is not recognized equally 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 with CMD /V:ON
or with SETLOCAL ENABLEDELAYEDEXPANSION
in Windows 2000 and after may be used to prove special characters stored in surround variables considering the variable value is expanded after the command was parsed:
C:\>cmd /V:ON Microsoft Windows [Version half-dozen.i.7601] Copyright (c) 2009 Microsoft Corporation. All rights reserved. C:\> set 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 fashion to implement a timed pause, as the PAUSE command halts script action indefinitely until any key is pressed.
Many workarounds were possible,[10] merely generally only worked in some environments: The Choice
command was non available in older DOS versions, PING
was just bachelor if TCP/IP was installed, and so on. No solution was bachelor from Microsoft, but a number of small utility programs, could be installed from other sources. A commercial instance would be the 1988 Norton Utilities Batch Enhancer (BE) command, where Be DELAY 18
would await for ane second, or the complimentary 94-byte WAIT.COM[11] where Await 5
would look for 5 seconds, then return command 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]
Normally, all printed text automatically has the control characters for wagon return (CR) and line feed (LF) appended to the stop of each line.
- batchtest.bat
-
C:\>batchtest.bat foo bar
-
It does non matter if the two echo commands share the aforementioned command line; the CR/LF codes are inserted to break the output onto separate lines:
C:\> @ echo Message ane&@ echo Message 2 Bulletin one Bulletin two
A play tricks 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 Bulletin 1, only does follow Line 2 and Line 3:
- batchtest2.bat
-
@ echo off set /p = "Bulletin 1" <nul echo Message 2 echo Bulletin iii
-
C:\>batchtest2.bat Message 1Message 2 Message three
-
This tin can be used to output information to a text file without CR/LF appended to the end:
C:\> set /p = "Message 1" <nul >data.txt C:\> set /p = "Message two" <nul >>information.txt C:\> set /p = "Message three" <nul >>data.txt C:\> type data.txt Message 1Message 2Message 3
However, there is no style to inject this stripped CR/LF prompt output direct into an environment variable.
Setting a Compatible Naming Convention (UNC) working directory from a shortcut [edit]
It is not possible to have a control prompt that uses a UNC path as the current working directory; east.grand. \\server\share\directory\
The control 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 C:\Windows\System32\
.
In Windows 2000 and after, a workaround is to use the PUSHD
and POPD
command with control extensions.[nb two]
If non enabled past default, command extensions can be temporarily enabled using the /Eastward:ON
switch for the command interpreter.
So to run a batch file on a UNC share, assign a temporary drive letter of the alphabet to the UNC share, and use the UNC share as the working directory of the batch file, a Windows shortcut can be synthetic 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.
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 effort to run a batch file as administrator from a network drive letter, using the correct-click file context menu, the functioning will unexpectedly fail. This is because the elevated UAC privileged account context does not take network drive letter assignments, and it is not possible to assign bulldoze letters for the elevated context via the Explorer shell or logon scripts. Withal, by creating a shortcut to the batch file using the above PUSHD
/ POPD
construct, and using the shortcut to run the batch file equally ambassador, the temporary drive letter will be created and removed in the elevated account context, and the batch file will function correctly.
The following 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\Control Processor
[12] allows the default directory to be UNC. CD
command will turn down to alter but placing a UNC path in Default Directory in a shortcut to Cmd or by using the Start command. start "" /d \\127.0.0.i\C$ "cmd /k"
(C$
share is for administrators).
Grapheme prepare [edit]
Batch files use an OEM graphic symbol set, every bit defined past the computer, due east.g. Code page 437. The non-ASCII parts of these are incompatible with the Unicode or Windows character sets otherwise used in Windows and so care needs to be taken.[13] Non-English file names piece of work only if entered through a DOS character set compatible editor. File names with characters outside this set do not piece of work in batch files.
To get output in Unicode into file pipes from an internal control such as dir
, one tin use the cmd /U
command. For example, cmd /U /C dir > files.txt
creates a file containing a directory list with right Windows characters, in the UTF-16LE encoding.
Batch viruses and malware [edit]
As with whatever other programming language, batch files tin can be used maliciously. Simple trojans and fork bombs are easily created, and batch files tin can do a course of DNS poisoning by modifying the hosts file. Batch viruses are possible, and tin can also spread themselves via USB flash drives by using Windows' Autorun capability.[14]
The following command in a batch file will delete all the information in the current directory (binder) - without starting time request for confirmation:
These three commands are a simple fork bomb that will continually replicate itself to deplete bachelor arrangement resources, slowing downward or crashing the organization:
: TOP start "" %0 goto TOP
Other Windows scripting languages [edit]
The cmd.exe control processor that interprets .cmd files is supported in all 32- and 64-bit versions of Windows up to at to the lowest degree Windows x[update]. COMMAND.EXE, which interprets .BAT files, was supported in all sixteen- and 32-bit versions upwards to at least Windows ten.[nb 3]
There are other, later and more powerful, scripting languages bachelor for Windows. Nevertheless, these require the scripting language interpreter to be installed before they can be used:
- KiXtart (.kix) — adult past 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 (.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 accept been a part of Windows since Windows 98.
- PowerShell (.ps1) — released in 2006 by Microsoft and can operate with Windows XP (SP2/SP3) and later versions. PowerShell tin can operate both interactively (from a command-line interface) and also via saved scripts, and has a potent resemblance to Unix shells.[15]
- Unix-fashion beat out 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. In that location are rules of precedence governing interpretation of, say, DoThis
if DoThis.com
, DoThis.exe
, DoThis.bat
, DoThis.cmd
, etc. be; by default DoThis.com
has highest priority. This default lodge may exist modified in newer operating systems past the user-settable PATHEXT environment variable.
Encounter also [edit]
- List of DOS commands
Notes [edit]
- ^ To verify that COMMAND.COM remains available (in the \WINDOWS\SYSTEM32 directory), type
Command.COM
at the 32-bit Windows vii command prompt. - ^ "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 creates a temporary bulldoze letter that points to that specified network resource and then change the electric current drive and directory, using the newly divers drive letter. Temporary drive letters are allocated from Z: on down, using the beginning unused drive letter found." --The help for PUSHD in Windows seven
- ^ Availability of CMD.EXE and Command.COM can be confirmed past invoking them in any version of Windows (Control.COM not in 64-chip versions; probably only bachelor in Windows eight 32-scrap versions if installed with option to back up 16-flake programs).
References [edit]
- ^ "Using batch files: Scripting; Direction Services". Technet.microsoft.com. 2005-01-21. Retrieved 2012-eleven-thirty .
- ^ Henry-Stocker, Sandra (2007-07-xviii). "Utilize your Unix scripting skills to write a batch file". itworld.com. IT World. Retrieved 2018-06-13 .
- ^ "Difference between bat and cmd | WWoIT - Wayne's World of IT". waynes-world-it.blogspot.fr. 2012-11-fifteen. Retrieved 2012-11-thirty .
- ^ "btm file extension :: all most the .btm file type". Cryer.co.uk. Retrieved 2012-eleven-30 .
- ^ Caldera DR-DOS 7.02 User Guide, Caldera, Inc., 1998 [1993, 1997], archived from the original on 2016-11-05, retrieved 2013-08-10
- ^ Brothers, Hardin; Rawson, Tom; Conn, King C.; Paul, Matthias R.; Dye, Charles E.; Georgiev, Luchezar I. (2002-02-27). 4DOS 8.00 online assist.
- ^ a b ".NET Cadre Runtime: Organization.Diagnostics.Procedure.Unix". GitHub . Retrieved 2020-02-11 .
2 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 part of the spec of code:ParseArgumentsIntoList, merely is uniform with CRT and .NET Framework.
- ^ a b Deley, David. "How Command Line Parameters Are Parsed".
- ^ "Child process documentation, section Windows Command Line, NodeJS PR #29576". GitHub . Retrieved 2020-02-11 .
- ^ "How to do a delay", ericphelps.com
- ^ Utilities for DOS, linking to WAIT.Cypher (annal of WAIT.COM) and other programs
- ^ a b https://support.microsoft.com/en-us/kb/156276 [ dead link ]
- ^ Chen, Raymond. "Keep your centre on the code page". Microsoft.
- ^ http://www.explorehacking.com/2011/01/batch-files-art-of-creating-viruses.html
- ^ "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 work
- Windows 10 batch file commands
- FreeDOS' FreeCOM : complete feature list
- Windows Control Line Interface script programming links
- scripting related information (also command line)
- dbenham. "How does the Windows Command Interpreter (CMD.EXE) parse scripts?". Stack Overflow.
Source: https://en.wikipedia.org/wiki/Batch_file
0 Response to "Dos Script to Read File Line by Line"
Postar um comentário