Skip to content Skip to sidebar Skip to footer

How to Read a Sertain Line and Char of a Text File Cmd

Script file for Microsoft computer operating systems

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

A batch file is a script file in DOS, OS/2 and Microsoft Windows. It consists of a series of commands to be executed past the command-line interpreter, stored in a apparently text file. A batch file may comprise any control the interpreter accepts interactively and employ 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, meaning "non-interactive execution", though a batch file might non process a batch of multiple information.

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 past allowing the user to ready a script to automate them. When a batch file is run, the shell program (ordinarily COMMAND.COM or cmd.exe) reads the file and executes its commands, normally line-by-line.[1] Unix-like operating systems, such as Linux, accept a similar, just more than flexible, type of file called a beat out 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, east.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 just to certain 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 fundamental. When DOS loads, the file AUTOEXEC.BAT, when present, is automatically executed, so whatever commands that demand to be run to gear up the DOS environment may be placed in this file. Computer users would have the AUTOEXEC.BAT file set the system appointment 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 information technology were a list of commands entered manually, with some extra batch-file-specific commands for bones 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 guild 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 earlier versions, one could run a .bat type file from Windows in the MS-DOS Prompt. Windows 3.1x and before, as well equally Windows 9x invoked COMMAND.COM to run batch files.

OS/two [edit]

The IBM OS/two operating system supported DOS-way batch files. Information technology also included a version of REXX, a more than avant-garde batch-file scripting language. IBM and Microsoft started developing this arrangement, merely during the structure of it broke upwards later a dispute; as a result of this, IBM referred to their DOS-like console beat out without mention of Microsoft, naming information technology just DOS, although this seemingly made no divergence with regard to the way batch files worked from COMMAND.COM.

OS/ii'southward batch file interpreter also supports an EXTPROC command. This passes the batch file to the plan named on the EXTPROC file equally a information file. The named program tin be a script file; this is similar to the #! mechanism.

Windows NT [edit]

Unlike Windows 98 and earlier, 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 different way, and then that the aforementioned batch file (with unlike extension) might work differently with cmd.exe and COMMAND.COM. In most cases, performance is identical if the few unsupported commands are non 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 apply certain cmd.exe-style batch files.

As of Windows eight[update], cmd.exe is the normal control interpreter for batch files; the older Control.COM can be run as well in 32-bit versions of Windows able to run sixteen-bit programs.[nb ane]

Filename extensions [edit]

.bat
The first 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 means the ii command interpreters execute batch files.
.cmd
Used for batch files in Windows NT family unit and sent to cmd.exe for estimation. COMMAND.COM does non recognize this file name extension, so cmd.exe scripts are not executed in the wrong Windows environs by mistake. In addition, append, dpath, ftype, set, path, assoc and prompt commands, when executed from a .bat file, alter the value of the errorlevel variable only upon an error, whereas from within a .cmd file, they would affect errorlevel even when returning without an error.[3] It is also used past IBM's Os/2 for batch files.
.btm
The extension used by 4DOS, 4OS2, 4NT and Accept Command. These scripts are faster, especially with longer ones, as the script is loaded entirely set up for execution, rather than line-by-line.[4]

Batch file parameters [edit]

Control.COM and cmd.exe support special variables (%0, %1 through %9) in order to refer to the path and name of the batch job and the offset nine calling parameters from within the batch task, see also SHIFT. Non-existent parameters are replaced by a goose egg-length string. They can be used similar to surroundings variables, but are non stored in the environment. Microsoft and IBM refer to these variables equally 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.[half dozen]

Examples [edit]

This example batch file displays How-do-you-do World!, prompts and waits for the user to printing a key, and so terminates. (Notation: It does not matter if commands are lowercase or uppercase unless working with variables)

                        @            ECHO            OFF            Repeat            Hello World!            PAUSE          

To execute the file, information technology 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 discussion processor working in plain text style.

When executed, the following is displayed:

Hello World! Press any central to continue . . .        

Caption [edit]

The interpreter executes each line in plow, starting with the start. The @ symbol at the start of whatsoever line prevents the prompt from displaying that command as information technology is executed. The control Echo OFF turns off the prompt permanently, or until it is turned on again. The combined @Echo OFF is often as here the first line of a batch file, preventing whatever commands from displaying, itself included. Then the side by side line is executed and the Echo How-do-you-do Globe! command outputs Howdy World!. The next line is executed and the PAUSE command displays Printing whatever key to keep . . . and pauses the script'southward execution. Subsequently a key is pressed, the script terminates, as there are no more than commands. In Windows, if the script is executed from an already running command prompt window, the window remains open at the prompt every bit 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 control, and thus variables which contain nada merely 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 argument:

parses as the erroneous construct:

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

                        IF            abc              def            ==bar            Repeat            Equal          

The usual way to foreclose this trouble is to surround 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 being compared to the variable must also be enclosed in quotes, because the quotes are not special delimiting syntax; these characters stand for themselves.

                        IF            "            %foo%            "            ==            "bar"            Repeat            Equal          

The delayed !VARIABLE! expansion available in Windows 2000 and later on may be used to avoid these syntactical errors. In this case, cipher or multi-word variables do not neglect syntactically considering the value is expanded after the IF command is parsed:

Another difference 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 cord. Example:

                        C:\>            set            MyVar            =            C:\>            repeat            %MyVar%            %MyVar%            C:\>            if            "            %MyVar%            "            ==            ""            (            repeat            MyVar is not divers)            else            (            echo            MyVar is            %MyVar%            )            MyVar is %MyVar%          

Batch interpreters prior to Windows 2000 would take displayed event 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 up past the crush into an array of strings, a Windows process receives the unabridged command-line as a single string, via the GetCommandLine API function. Every bit a outcome, each Windows application can implement its ain parser to split the entire command line into arguments. Many applications and command-line tools have evolved their own syntax for doing that, and then in that location is no unmarried convention for quoting or escaping metacharacters on Windows control lines.

  • For some commands, spaces are treated as delimiters that carve up arguments, unless those spaces are enclosed by quotation marks. Diverse conventions exist of how quotation marks can be 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 role. It uses the convention that iin backslashes followed by a quotation mark (") produce n backslashes followed by a begin/end quote, whereas (2n)+1 backslashes followed by a quotation marker once again produce n backslashes followed by a quotation marking literal. The aforementioned convention is part of the .Internet Framework specification.[7]
      • An undocumented attribute is that "" occurring in the middle of a quoted cord produces a single quotation mark.[seven] (A CRT change in 2008 [msvcr90] modified this undocumented handling 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 concluded.)
    • Another convention is that a single quotation mark (") is not included as function of the string. However, an escaped quotation mark (""") can be part of the cord.[ commendation needed ]
    • Yet another common convention comes from the use of Cygwin-derived ported programs. It does not differentiate betwixt backslashes occurring earlier or not earlier quotes. Run across glob (programming) § Windows and DOS for information on these alternative command-line parsers.[9]
    • Some important Windows commands, like cmd.exe and wscript.exe, utilize their own rules.[8]
  • For other commands, spaces are not treated as delimiters and therefore do not 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 exist inserted into some other line of text that must also be enclosed in quotation marks, particular attention to the quoting mechanism is required:

                        C:\>            fix            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 i /50 Arrangement /SO            "Source"            /D            "Example:                        %foo%            "            Fault: Invalid Argument/Option - 'cord'.            Blazon "EVENTCREATE /?" for usage.          

On Windows 2000 and later, the solution is to supplant each occurrence of a quote graphic symbol within a value by a serial of three quote characters:

                        C:\>            set            foo            =            "this cord 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 /50 System /SO            "Source"            /D            "Example:                        %foo%            "            SUCCESS: A 'Alert' type event is created in the 'Source' log/source.          

Escaped characters in strings [edit]

Some characters, such as pipe (|) characters, have special pregnant 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 not recognized equally an internal or external control,            operable plan or batch file.            C:\>            Echo            foo            ^|            bar            foo | bar          

Still, escaping does non work every bit expected when inserting the escaped character into an surround variable. The variable ends up containing a live pipe command when only echoed. It is necessary to escape both the caret itself and the escaped graphic symbol for the grapheme display as text in the variable:

                        C:\>            gear up            foo            =bar            |            baz            'baz' is non recognized as an internal or external command,            operable plan or batch file.            C:\>            set            foo            =bar            ^|            baz            C:\>            repeat            %foo%            'baz' is not recognized as an internal or external command,            operable program or batch file.            C:\>            fix            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 later may be used to show special characters stored in environment variables considering the variable value is expanded after the control was parsed:

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

Sleep or scripted filibuster [edit]

Until the TIMEOUT command was introduced with Windows Vista, there was no piece of cake way to implement a timed pause, as the PAUSE command halts script activeness indefinitely until any central is pressed.

Many workarounds were possible,[10] simply by and large only worked in some environments: The Pick command was not bachelor in older DOS versions, PING was only available if TCP/IP was installed, and and then on. No solution was available from Microsoft, but a number of small utility programs, could exist installed from other sources. A commercial example would be the 1988 Norton Utilities Batch Enhancer (BE) control, where Exist Delay 18 would wait for 1 second, or the gratis 94-byte Expect.COM[eleven] where Look 5 would expect for 5 seconds, and then render control to the script. Well-nigh such programs are 16-bit .COM files, so are incompatible with 64-scrap Windows.

Text output with stripped CR/LF [edit]

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

  • batchtest.bat
                                            C:\>batchtest.bat                    foo                    bar                  

Information technology does not thing if the two echo commands share the same command line; the CR/LF codes are inserted to suspension the output onto separate lines:

                        C:\>            @            repeat            Bulletin 1&@            echo            Message two            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 case, the CR/LF does not follow Message ane, only does follow Line 2 and Line three:

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

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

                        C:\>            set            /p            =            "Message 1"            <nul            >information.txt            C:\>            set            /p            =            "Message 2"            <nul            >>data.txt            C:\>            ready            /p            =            "Message iii"            <nul            >>data.txt            C:\>            blazon            data.txt            Message 1Message 2Message 3          

However, there is no way to inject this stripped CR/LF prompt output direct into an environment variable.

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

It is not possible to have a control prompt that uses a UNC path every bit the current working directory; e.k. \\server\share\directory\

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

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

If non enabled past default, control extensions can be temporarily enabled using the /Due east: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 tin 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.

This also solves a problem related to User Account Control (UAC) on Windows Vista and newer. When an ambassador is logged on and UAC is enabled, and they endeavor 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 considering the elevated UAC privileged account context does not have network drive letter assignments, and it is not possible to assign bulldoze letters for the elevated context via the Explorer vanquish or logon scripts. However, 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 of the alphabet will be created and removed in the elevated business relationship context, and the batch file volition part correctly.

The following syntax does correctly expand to the path of the current batch script.

%~dp0        

UNC default paths are turned off past 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 control will refuse to change but placing a UNC path in Default Directory in a shortcut to Cmd or past using the Start command. start "" /d \\127.0.0.one\C$ "cmd /yard" (C$ share is for administrators).

Character prepare [edit]

Batch files use an OEM character set, as defined past 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.[xiii] Non-English file names work only if entered through a DOS grapheme gear up uniform editor. File names with characters outside this set exercise not work in batch files.

To get output in Unicode into file pipes from an internal control such as dir, ane can use the cmd /U control. For example, 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 whatever other programming linguistic communication, batch files can exist used maliciously. Unproblematic trojans and fork bombs are easily created, and batch files can do a form of DNS poisoning past modifying the hosts file. Batch viruses are possible, and tin also spread themselves via USB wink drives by using Windows' Autorun capability.[14]

The post-obit command in a batch file will delete all the information in the current directory (folder) - without showtime asking for confirmation:

These three commands are a simple fork flop that will continually replicate itself to deplete available organization resources, slowing down or crashing the system:

                        :            Superlative            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 least Windows 10[update]. COMMAND.EXE, which interprets .BAT files, was supported in all sixteen- and 32-chip versions up to at least Windows 10.[nb three]

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

  • KiXtart (.kix) — adult 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 a .cmd file.
  • Windows Script Host (.vbs , .js and .wsf) — released past 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 style (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 afterward versions. PowerShell can operate both interactively (from a control-line interface) and also via saved scripts, and has a stiff resemblance to Unix shells.[xv]
  • Unix-style beat scripting languages tin can exist used if a Unix compatibility tool, such as Cygwin, is installed.
  • Cross-platform scripting tools including Perl, Python, Crimson, Rexx, Node.js and PHP are bachelor for Windows.

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

Meet also [edit]

  • List of DOS commands

Notes [edit]

  1. ^ To verify that COMMAND.COM remains bachelor (in the \WINDOWS\SYSTEM32 directory), type COMMAND.COM at the 32-fleck Windows 7 command prompt.
  2. ^ "If Command Extensions are enabled the PUSHD control accepts network paths in add-on 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 and so alter the current drive and directory, using the newly defined drive letter. Temporary drive messages are allocated from Z: on down, using the first unused drive letter of the alphabet found." --The help for PUSHD in Windows seven
  3. ^ Availability of CMD.EXE and Control.COM tin can exist confirmed by invoking them in any version of Windows (COMMAND.COM not in 64-bit versions; probably but bachelor in Windows eight 32-fleck versions if installed with option to support 16-flake programs).

References [edit]

  1. ^ "Using batch files: Scripting; Management Services". Technet.microsoft.com. 2005-01-21. Retrieved 2012-11-30 .
  2. ^ Henry-Stocker, Sandra (2007-07-18). "Utilise your Unix scripting skills to write a batch file". itworld.com. It World. Retrieved 2018-06-xiii .
  3. ^ "Difference between bat and cmd | WWoIT - Wayne's World of Information technology". waynes-world-information technology.blogspot.fr. 2012-11-15. Retrieved 2012-11-30 .
  4. ^ "btm file extension :: all about the .btm file type". Cryer.co.united kingdom of great britain and northern ireland. Retrieved 2012-11-xxx .
  5. ^ Caldera DR-DOS 7.02 User Guide, Caldera, Inc., 1998 [1993, 1997], archived from the original on 2016-xi-05, retrieved 2013-08-10
  6. ^ Brothers, Hardin; Rawson, Tom; Conn, Rex C.; Paul, Matthias R.; Dye, Charles Eastward.; Georgiev, Luchezar I. (2002-02-27). 4DOS eight.00 online help.
  7. ^ a b ".Cyberspace 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 behavior is not part of the spec of code:ParseArgumentsIntoList, just 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-11 .
  10. ^ "How to do a delay", ericphelps.com
  11. ^ Utilities for DOS, linking to Expect.Zero (archive of WAIT.COM) and other programs
  12. ^ a b https://support.microsoft.com/en-usa/kb/156276 [ dead link ]
  13. ^ Chen, Raymond. "Proceed your eye on the code folio". Microsoft.
  14. ^ http://world wide web.explorehacking.com/2011/01/batch-files-fine 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 10 batch file commands
  • FreeDOS' FreeCOM : complete feature list
  • Windows Command Line Interface script programming links
  • scripting related data (too command line)
  • dbenham. "How does the Windows Command Interpreter (CMD.EXE) parse scripts?". Stack Overflow.

gustintrah1938.blogspot.com

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

Post a Comment for "How to Read a Sertain Line and Char of a Text File Cmd"