Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Hands teach you to write batches


May 23, 2021 DOS Command learning manual



Hands teach you to write batches (willsort instalment version)




Climbing brother can be said to be well-intentioned, by its feelings, slightly tight and meager force; the original content is not easy, only under each paragraph to add a note, its text is mostly not for error correction, more years of experience, or occasional, or gradually realized, inevitably biased; Righteous contrary, please axe positive;

In addition, it is suggested that Climbing brother's essays should not be confined to the domestic, such technical articles, the internal and external levels are very different;




--------------------------------------------------------

Title: Hand-in-hand teaches you to write a batch-batch introduction

Author: Name

Editing by Climbing

Source: China DOS Alliance Joint DOS Forum

Caption: willsort

Date: 2004-09-21

--------------------------------------------------------

An introduction to batching



A file with an extension of bat (which can also be cmd under nt/2000/xp/2003) is a batch file.


The willsort comment is noted

.bat is a batch file under dos

.cmd is another batch file for the nt kernel command line environment

More broadly, unix's shell scripts, as well as other operating systems and even applications, are interpreted and executed by shells, much like batch files, and are also interpreted by specialized interpreters in behavior units, a more common term for scripting languages. S o from a certain degree of analysis, batch, unix shell, awk, basic, perl and other scripting languages are the same, but the scope of the application and interpretation of the platform are different. Even some applications still use the term batch, and their contents and extensions are completely different from dos batch processing.

========================================================================


The first batch file is a text file, each line of which is a DOS command (most of the time it's like the command line we execute at the DOS prompt), and you can create and modify batch files using any text file editing tool, such as Edit under DOS or Windows Notepad.


Willsort caption

Non-dos commands are fully available in batch files, and even ordinary data files that do not have executable properties, due to the involvement of windows systems as a new interpretation platform, making batch applications increasingly "marginalized". So the batch we're talking about should be limited to the dos environment or the command-line environment, otherwise a lot of ideas and settings need to change a lot.

========================================================================


Second, a batch file is a simple program that controls the flow of commands through conditional statements (ifs) and process control statements (goto), and you can also use circular statements (for) to loop through a command in a batch. O f course, the programming ability of batch files is very limited and very irregular compared with programming statements such as C language. A batch program statement is a DOS command that includes internal and external commands, and the ability to batch depends largely on the command you are using.


The willsort comment is noted

Batch file can also be called a batch program, which is different from a compiled language, where a file with an extension of c or cpp can be called a c-language file or a c-language source code, but only a compiled connected exe file can be called a c-language program. Because the batch files themselves have both the readability of the text and the executability of the program, the boundaries of these terms are blurred.

========================================================================


Third, each written batch file is equivalent to an external COMMAND for DOS, and you can put the directory in which it resides into your DOS search path so that it can run anywhere. It is a good practice to set up a bat or batch directory on your hard drive (e.g., C:\BATCH) and then put all the batch files you write into that directory so that you can run all the batch programs you write anywhere by setting c:\batch in path.


The willsort comment is noted

In the case of dos systems, executables can be subdivided into about five categories, ranked from highest to lowest according to execution priority: DOSKEY macro command (pre-resident memory), COMMAND. I nternal commands in COM (ready to enter memory depending on the environment of memory), executables with com as extensions (loaded directly into memory by command.com), executables with exe bit extensions (repositioned by command.com and loaded into memory), batch analyzers with bat extensions (interpreted by command.com, called 2, 3, 4, 5 executables in order of priority, analyzed first line, and executed a line , the file itself does not load memory)

========================================================================


Fourth, under the DOS and Win9x/Me systems, the AUTOEXEC.BAT batch file under the C: root directory is an automatic batch file that runs automatically every time the system starts, and you can put the commands that the system runs every time you start into the file, such as setting the search path, turning into the mouse driver and disk cache, setting the system environment variables, and so on. Here's an example of an autoexec .bat Windows 98:

@ECHO OFF

PATH C:\WINDOWS; C :\WINDOWS\COMMAND; C :\UCDOS; C :\DOSTools; C :\SYSTOOLS; C :\WINTOOLS; C:\BATCH

LH SMARTDRV. EXE /X

LH DOSKEY.COM /INSERT

LH CTMOUSE. Exe

SET TEMP=D:\TEMP

SET TMP=D:\TEMP


The willsort comment is noted

AUTOEXEC. BAT is an automatically running batch file for the DOS system, which is interpreted COMMAND.COM the startup of the system;

In the Win9x environment, support for DOSSTART has not only been increased. B AT, WINSTART. M any other automatically running batch files, such as BAT, have also increased .BAT AUTOEXEC. D os. W 40 . B ak. O LD . Many variants, such as PWS, adapt to complex environments and changing needs.

========================================================================


--------------------------------------------------------

Title: Hand-in-Hand teaches you to write batch - common commands with special commands

Author: Name

Editing by Climbing

Source: China DOS Alliance Joint DOS Forum

Caption: willsort

Date: 10 November 2004

--------------------------------------------------------


(Repost and perfect) hand-in-hand to teach you to write batch

The original author wrote very unscionable, the article is simply wrong, and if not modified and perfected, it is simply the wrong child, therefore, I made changes on the basis of the original text, corrected most of the errors (of course, inevitably there may be new mistakes, hope that the master found in time to point out).


URL: http://www.txwm.com/News/technic/200408/2004081609515074304.html


Excerpted from: World Internet Cafe Alliance Author: Name

Modification and improvement: Climbing([email protected])

Last modified: 19 August 2004



The willsort comment is noted

The following classification of commands, there is a lot to consider. T his is not a command in a common command, , while commands such as dir copy, which are also common, are not included, and all commands in a special command are common commands for me. I t is recommended that the batch referenced commands be divided into internal commands, external commands, third - party programs three categories. One of the different types of internal and external commands is that commands that are dedicated to or commonly used in batch processing can be called "batch commands".

The following excerpts from MS-DOS 6.22 help documentation about "batch commands", of course, some of these concepts and definitions are already somewhat behind.


Batch command

A batch file or batch program is a body file that contains several MS-DOS commands, extended to . B AT。 MS-DOS executes commands in this batch in groups when the name of the batch is knocked in at the command prompt.

Any commands that can be used at the command prompt are available in the batch program. In addition, the following MS-DOS commands are specifically used in batch programs.

<Call> <If>

<Choice> <Pause>

<Echo> <Rem>

<For> <Shift>

<Goto>

========================================================================


Common commands


Echo, call, pause, rem (tip: use:: instead of rem) are some of the most common commands for batch files, and we'll start with them.


The willsort comment is noted

First of all, it is not a command, but a special marker for the DOS batch, which is only used to mask command line echo. Here are some special markers that you might see on the DOS command line or in a batch:

CR (0D) command line end character

Escape (1B) ANSI escape character guide

Space (20) is a commonly used parameter definer

Tab(09) ; - Not commonly used parameter definers

The COPY command file connector

* ? File wildcard

"" String definer

| The command pipe character

< > >> File redirector

@ The command line echo mask

/ The parameter switch guide

: Batch label guide

% The batch variable guide


Second, :: can indeed play the role of rem comments, and more concise and effective; B ut there are two things to note:

First, in addition to :: any line of characters beginning with : is treated as a label in the batch, and ignores everything that follows directly, just to distinguish itself from the normal label, it is recommended to use a label that goto cannot recognize, that is, a special symbol immediately after: followed by a non-alphanumeric number.

Second, unlike rem, :: after the character line does not echo when executed, whether or not to open the command line echo state with echo on, because the command interpreter does not consider him to be a valid command line, from this point of view, rem in some cases will be more applicable than:: I n addition, rem can be used in config .sys files.

========================================================================


Echo represents the character after this command is displayed

Echo off means that all running commands after this statement do not display the command line itself

It looks like echo off, but it is added to the front of each command line, indicating that the runtime does not display the command line for that line (only the current line is affected).

Call calls another batch file (if you call another batch file directly without call, you will not be able to return the current file and execute subsequent commands for the current file after executing that batch file).

Pause running this sentence pauses batch execution and displays Press any key to continue on the screen... t o wait for the user to press any key before continuing

Rem indicates that the character after this command is the line of interpretation (comment), which is not executed, but is for future reference (equivalent to a comment in a program).


The willsort comment is noted

The description here is confusing, and it's better to help with the command line that directly references a command


----------------------------------------------------------------------------

ECHO


When the program is running, the body in the batch program is displayed or hidden. It can also be used to allow or disable echoes of commands.

When you run a batch program, MS-DOS typically displays (echo) commands in the batch program on the screen.

Use the ECHO command to turn off this feature.

Grammar

ECHO [ON| OFF]

To display a command with the echo command, you can use the following syntax:

echo [message]

Parameters

ON| OFF

Specify whether to allow the echo of the command. To display the current ECHO settings, use echo without parameters

Command.

message

Specifies the body that lets MS-DOS appear on the screen.


----------------------------------------------------------------------------

CALL

Calling another batch from one batch does not cause the first batch to abort.

Grammar

CALL [drive:][path]filename [batch-parameters]

Parameters

[drive:] [path]filename

Specify the name of the batch program to call and where it is stored. T he file name must be used. BAT is an extension.

batch-parameters

Specify the command line information required by the batch.


----------------------------------------------------------------------------

PAUSE

Pause the execution of the batch and display a message that prompts the user to press any key to continue execution. Only in batches

use this command in the program.

Grammar

PAUSE

----------------------------------------------------------------------------

Rem

Add annotations to a batch .SYS or CONFEG file. ReM commands can also be used to mask commands (in CONFIG .SYS).

The REM command can also be ;) (or not), but not in batch files.

Grammar

REM [string]

Parameters

string

Specify the command to mask or the annotations to include.

========================================================================


Example 1: Edit the a.bat file with edit, enter the following contents after the deposit is c:\a.bat, after executing the batch file can be implemented: write all the files in the root directory to a.txt, start UDOS, enter WPS and other functions.


The contents of the batch file are: command comments:


@echo off does not display subsequent and current command lines

Dir c: ..txt . .txt

Call c: sucdos s ucdos.bat ucdos call ucdos

echo hello show "hello"

Pause pause and wait for the button to continue

rem ready to run wps comment: Ready to run wps

cd ucdos enters the ucdos directory

wps runs wps


The parameters of the batch file


Batch files can also use parameters (equivalent to command-line parameters for DOS commands) like functions in the C language, which requires an argument notation "%".


%[1-9) represents a parameter, which refers to a string separated by a space (or tab) that is added to the file name when the batch file is run. V ariables can be represented from %0 to %9, %0 for the batch command itself, and other parameter strings are represented in %1 to %9 order.


Example 2: C: There is a batch of processing files named f.bat under the root directory.

@echo off

format %1


If you perform C:\gt;f a:

Then when you .bat f-1, %1 means a:, so that forat %1 is equivalent to forat a:, so that the above command runs when the actual execution is form a:


Example 3: C: The next batch of processing files in the root is .bat, and the contents are:

@echo off

type %1

type %2


Then run C:\t a.txt b.txt

%1 : represents .txt

%2: represents .txt

The above commands then display the contents of the .txt and b .txt in order.


The willsort comment is noted

Arguments are also processed as variables in batch processing, so the percent sign is also used as a guide, followed by a number in 0-9 that forms a parameter reference. T he relationship between the reference and the argument (for example, %1 and a:) above is similar to the relationship between the variable pointer and the variable value. W hen we want to reference the eleventh or more parameters, we must move the doS parameter start pointer. T he shift command is acting as the role of this moving pointer, moving the starting pointer of the argument to the next argument, similar to the pointer operation in the C language. The illustration is as follows:


The initial state, cmd as the command name, can be used with %0 Reference

cmd arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8 arg9 arg10

^    ^    ^    ^    ^    ^    ^    ^    ^    ^

|    |    |    |    |    |    |    |    |    |

%0 %1 %2 %3 %4 %5 %6 %7 %8 %9


After 1 shift, cmd will not be referenced

cmd arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8 arg9 arg10

^    ^    ^    ^    ^    ^    ^    ^    ^    ^

|    |    |    |    |    |    |    |    |    |

%0 %1 %2 %3 %4 %5 %6 %7 %8 %9


After 2 shifts, arg1 is also discarded, and %9 points empty, with no reference meaning

cmd arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8 arg9 arg10

^    ^    ^    ^    ^    ^    ^    ^    ^

|    |    |    |    |    |    |    |    |

%0 %1 %2 %3 %4 %5 %6 %7 %8


Unfortunately, neither win9x and DOS support shift inverse operation. Shift supports the /n parameter only in the nt kernel command line environment, and the starting pointer can be moved back with the first argument as the base.

========================================================================



Special commands



If goto choice for is a more advanced command in a batch file, and if you're skilled with these, you're an expert in batch files.




First, if is a conditional statement that determines whether a specified condition is met and thus determines the execution of a different command. T here are three formats:


1, if (not) "parameters" and "strings" of commands to be executed


If the argument is equal to the string specified (not represents inequality, the same between), then the condition is true, the command is run, or the next sentence is run.


Example: if "%1"""a" format a:


The willsort comment is noted

The description of this point in if's command-line help is:

IF [NOT] string1==string2 command

Here are a few points to note:

1. Double quotation marks containing strings are not necessary for syntax, but are only a customary "anti-aircraft" character

2. String1 is not necessarily an argument, it can also be an environment variable, a loop variable, and other string constants or variables

3. Command is not required by syntax, and string2 is followed by a space to form a valid command line

========================================================================


2, if (not) exist (path) file name to be executed command

If there is a specified file, the condition is true, run the command, or run the next sentence.


e.g.: if exist c: s config.sys type c: s config .sys

Indicates that if there is a c:.sys file, the contents of it are displayed.


Willsort Notes

You can also use the following:

if exist <device> command

Device refers to a device that is loaded in a DOS system and is usually:

AUX, PRN, CON, NUL

COM1, COM2, COM3, COM4

LPT1, LPT2, LPT3, LPT4

XMSXXXX0, EMMXXXX0

A: B: C: ...,

CLOCK$, CONFIG$, DblBuff$, IFS$HLP$

The specific content will vary slightly depending on the hardware environment, and the following three points need to be guaranteed when using these device names:

1. The device does exist (except for devices virtually by software)

2. The device driver is loaded (standard devices such as aux, prn, etc. are defined by system default)

3. The device is ready (mainly a: b: ..., com1..., lpt1...) etc.)

You can use the command mem/d | Find "device" /i to review the devices loaded in your system

In addition, in THE DOS system, the device is also considered to be a special file, and the file can also be called a character device; B ecause devices and files are managed using handles, handles are names, similar to file names, except that handles are not applied to disk management, but to memory management, so-called device loading also refers to assigning referenceable handles to them in memory.

========================================================================


3, if errorlevel and lt; digital commands to be executed


Many DOS programs return a numeric value at the end of the run to represent the result (or state) of the program's run, and the if errorlevel command allows you to determine the return value of the program and decide to execute different commands based on different return values (return values must be in order from large to small). If the return value is equal to the specified number, the condition is established and the command is run, otherwise the next sentence is run.


Such as if errorlevel 2 goto x2


The willsort comment is noted

The order in which return values are arranged from large to small is not necessary, but is simply a customary use when the command is executed as goto, and when you use set as the execution command, it is usually arranged from small to large, for example, when you want to place the return code in an environment variable, you need to use the following order:

if errorlevel 1 set el=1

if errorlevel 2 set el=2

if errorlevel 3 set el=3

if errorlevel 4 set el=4

if errorlevel 5 set el=5

...


Of course, you can also use the following loop instead, the principle is consistent:

for %%e in (1 2 3 4 5 6 7 8...) do if errorlevel %%e set el=%%e


For more efficient and concise use, you can refer to another article I wrote about getting errorlevel


The reason for this phenomenon is that if errorlevel compares the return code's judgment conditions are not equal to, but greater than equal to. D ue to goto's jump characteristics, sorting from small to large causes a jump at a smaller return code; And because of the set command's "repeat" assignment characteristics, sorting from large to small results in smaller return codes "overwriting" larger return codes.


In addition, while the if errorlevel-and-lt; number command is also a valid command line, it is only command.com that is ignored when interpreting the command line as a command line slice

========================================================================



Second, goto batch file running here will jump to the goto specified label (label name is label, label with: followed by a standard string to define), goto statements are generally used with if, according to different conditions to execute different command groups.


Such as:


goto end


:end

echo this is the end


The label is defined by ":string" and the line where the label is located is not executed.


The willsort comment is noted

Labels are often translated as "labels", but this is not broadly agreed.


Goto and .lt;label> combined with the :-lt;label-gt; can achieve a jump in the middle of execution, combined with if to implement the conditional branch of the execution process, multiple ifs can implement the grouping of commands, similar to the switch case structure in C or the select case structure in Basic, large-scale and structured command grouping can achieve functional functions in the high language. Here's a comparison of batch and C/Basic in syntax structure:


Batch C / Basic

goto&: goto&:

goto&:&if if{}&else{} / if&elseif&endif

goto&:&if... switch&case / select case

goto&:&if&set&envar... function() / function(),sub()

========================================================================


Third, choice uses this command to allow the user to enter a character (for selection), so that according to the user's choice to return a different errorlevel, and then in the if errorlevel, according to the user's choice to run different commands.


Note: Choice commands are external commands for DOS or Windows systems, different versions of the choice command syntax will be slightly different, please use choice /?


Choice's command syntax (the syntax is the syntax of the choice command in Windows 2003, and the command syntax of other versions of the choice is much the same):


CHOICE [/C choices] [/N] [/CS] [/T timeout /D choice] [/M text]


Describe:

The tool allows the user to select an item from the selection list and return an index of the selected item.


List of parameters:

/Choices specifies a list of options to create. The default list is "YN".


/N Hide the list of options in the prompt. Prompt the previous message to be displayed,

The option is still enabled.


/CS allows you to select the case-split option. By default, this tool

It's caseless.


The number of seconds paused before /T timeout makes the default selection. The acceptable value is from 0

to 9999. If 0 is specified, there is no pause, the default option

will get a choice.


/D choice specifies the default option after nnnn seconds. Characters must be selected with /C

item specified in a set of selections; At the same time, nnnn must be specified with /T.


/M text specifies the message to be displayed before the prompt. If not specified, the tool only

Displays a prompt.


/? A help message is displayed.


Attention:

The ERRORLEVEL environment variable is set to the key index selected from the selection set. The first selection listed

Select return 1, second option return 2, and so on. If the key the user presses is not a valid selection,

The tool will sound a warning. If the tool detects an error state, it returns 255

ERRORLEVEL value. If the user presses the Ctrl-Break or Ctrl-C keys, the tool returns 0

ERRORLEVEL value. When the ERRORLEVEL parameter is used in a batch program, the parameter is lowered

order.


Example:

CHOICE /?

CHOICE /C YNC/M "Confirm press Y, press N, or cancel press C."

CHOICE /T 10 /C ync /CS /D y

CHOICE /C ab /M "Option 1 Please select a, option 2 please select b."

CHOICE /C ab /N/M"Option 1 Select a, Option 2 Select b."


The willsort comment is noted

I list win98 under the use of choice help, has been distinguished


Waits for the user to choose one of a set of choices.

Wait for the user to select one of a set of characters to be selected


CHOICE [/C[:]choices] [/N] [/S] [/T[:]c,nn] [text]


/C[:]choices Specifies allowable keys. Default is YN

Specifies the allowed keys (characters to be selected), which defaults to YN

/N Do not display choices and ? at end of prompt string.

Question marks and characters to be selected in the prompt string are not displayed

/S Treat choice keys as case sensitive.

Case sensitive when working with characters to be selected

/T[:]c,nn Default choice to c after nn seconds

Select c by default after nn seconds

text Prompt string to display

The prompt string to display

ERRORLEVEL is set to offset of key user presses in choices.

ERRORLEVEL is set to the offset value of the character typed by the user in the character to be selected

========================================================================

If I run the command: CHOICE /C YNC/M "Confirm press Y, press N, or cancel press C."

On the screen, you'll see:

Confirm that press Y, no, N, or cancel, press C. [Y,N,C]?

Example: the contents .bat the test data are as follows (note that when you use if errorlevel to determine the return value, arrange the return value from highest to thud):

@echo off

choice /C dme /M "defrag,mem,end"

if errorlevel 3 goto end

if errorlevel 2 goto mem

if errotlevel 1 goto defrag


The willsort comment is noted

errotlevel -> errorlevel

========================================================================


:defrag

c:\dos\defrag

goto end


:mem

Mem

goto end


:end

echo good bye


After this batch is run, "defrag, mem, end[D, M, E??" is displayed, the user can select d m e, and then the if statement is judged according to the user's choice, d indicates the execution of the program segment labeled defrag m indicates the execution of a program segment labeled mem, e indicates the execution of a program segment labeled end, each segment ends with goto end to jump the program to the end mark, and then the program will display good bye, the batch run ends.




Four, for loop command, as long as the conditions meet, it will execute the same command more than once.


Grammar:

A specific command is executed on each file in a set of files.


FOR %%variable IN (set) DO command [command-parameters]


%%variable specifies a single-letter replaceable parameter.

(set) specify one or a set of files. Wildcards can be used.

Command specifies the commands that are executed for each file.

command-parameters

Specify parameters or command-line switches for a specific command.


For example, there is a line in a batch file:

for %%c in (*.bat *.txt) do type %%c


The command line displays the contents of all files in the current directory with bat and txt as extensions.


The willsort comment is noted

It should be noted that when a string in () is not a single or multiple file name, it will simply be replaced as a string, a feature coupled with the attribute in () that can be embedded in multiple strings, and it is clear that for can be thought of as a traversal loop.

Of course, in the command-line environment of the nt/2000/xp/2003 series, for is given more features, allowing it to analyze command output or strings in files, and there are many switches used to extend the file replacement function.

========================================================================


--------------------------------------------------------

Title: Hand-in-hand teaches you to write batch-batch examples

Author: Name

Editing by Climbing

Source: China DOS Alliance Joint DOS Forum

Caption: willsort

Date: 10 November 2004

--------------------------------------------------------


(Repost and perfect) hand-in-hand to teach you to write batch


The original author wrote very unscionable, the article is simply wrong, and if not modified and perfected, it is simply the wrong child, therefore, I made changes on the basis of the original text, corrected most of the errors (of course, inevitably there may be new mistakes, hope that the master found in time to point out).


URL: http://www.txwm.com/News/technic/200408/2004081609515074304.html


Excerpted from: World Internet Cafe Alliance Author: Name

Modification and improvement: Climbing([email protected])

Last modified: 19 August 2004


An example of batch processing


1. IF-EXIST


1) Start with a note book in C: . . . build a test1 .bat batch file, the contents of which are as follows:

@echo off

IF EXIST \AUTOEXEC. B AT TYPE \AUTOEXEC. B AT

IF NOT EXIST \AUTOEXEC. B AT ECHO \AUTOEXEC. B AT does not exist


Then run it:

C:\>TEST1. B AT


If C:/exists with autoexEC.BAT, its contents will be displayed, and if it does not exist, the batch will prompt you that the file does not exist.


2) Then a test2 document is .bat, which reads as follows:

@ECHO OFF

IF EXIST \%1 TYPE \%1

IF NOT EXIST \%1 ECHO \%1 does not exist


Perform:

C:\>TEST2 AUTOEXEC. B AT

The command runs with the same results as above.


Description:

(1) IF EXIST is used to test the existence of a file in the format

IF EXIST (Paths and File Names) command

(2) the %1 in the test2.bat file is the parameter, doS allows the transmission of 9 batch parameter information to the batch file, respectively% 1 to %9 (%0 for test2 command itself), which is a bit like the relationship between the argument and the parameter in programming, %1 is the parameter, AUTOEXEC. B AT is a real ginseng.


The willsort comment is noted

DOS does not have a limit of "allows the transmission of 9 batches of parameter information", the number of parameters is limited only by the length of the command line and the processing power of the called command. H owever, in the batch program, only 10 parameters can be referenced at the same time, because DOS only gives the ten parameter references from %0 to %9.

========================================================================


3) Further, establish a document called Test3.BAT, which reads as follows:

@echo off

IF "%1" == "A" ECHO XIAO

IF "%2" == "B" ECHO TIAN

IF "%3" == "C" ECHO XIN


If you run:

C:\>TEST3 A B C

On the screen, you'll see:

XIAO

TIAN

XIN


If you run:

C:\>TEST3 A B

It will appear on the screen

XIAO

TIAN


During this command execution, DOS specifies an empty string to parameter %3.


2、IF-ERRORLEVEL


Establish the TEST4 .BAT as follows:

@ECHO OFF

XCOPY C:\AUTOEXEC. BAT D:\

IF ERRORLEVEL 1 ECHO file copy failed

IF ERRORLEVEL 0 ECHO successfully copied the file


Then execute the file:

C:\>TEST4


If the file copy is successful, the screen will display "Successful copy of the file" or it will show "File copy failed".


IF ERRORLEVEL is used to test the return value of its last DOS command, note that it is only the return value of the last command, and the return value must be determined in order from large to small.

Therefore, the following batch file is wrong:


@ECHO OFF

XCOPY C:\AUTOEXEC. B AT D:\

IF ERRORLEVEL 0 ECHO successfully copied the file

IF ERRORLEVEL 1 ECHO did not find the copy file

IF ERRORLEVEL 2 ECHO users abort copy operations via ctrl-c

IF ERRORLEVEL 3 ECHO preset error prevents file copy operations

If ERRORLEVEL 4 ECHO copy process write disk error


Whether the copy was successful or not, the following:


The copy file was not found

The user aborts the copy operation through ctrl-c

Preset errors prevent file copy operations

There was an error writing during the copy


will be displayed.


Here are the return values of several common commands and what they represent:


backup

0 The backup was successful

1 The backup file was not found

2 File sharing conflicts prevent backups from completing

3 The user aborts the backup with ctrl-c

4 The backup operation was aborted due to a fatal error


diskcomp

The 0 disk comparison is the same

1 plate is different

2 The user aborts the comparison operation through ctrl-c

3 The comparison operation was aborted due to a fatal error

4 Preset error aborts comparison


diskcopy

The 0 disk copy operation was successful

1 Non-fatal disc read/write error

2 The user ends the copy operation through ctrl-c

3 The disk copy was aborted due to a fatal processing error

4 Preset errors prevent copy operations


format

0 Format was successful

3 The user aborts the formatting process through ctrl-c

4 Formatting aborted due to a fatal processing error

5 In the prompt "proceed with format (y/n)?" N ext the user types n to end


Xcopy

0 The file was copied successfully

1 The copy file was not found

2 The user aborts the copy operation through ctrl-c

4 Preset errors prevent file copy operations

5 Write disk error during copy


The willsort comment is noted

chkdsk

0 The error was not found

255 One or more errors were found


choice

0 The user presses ctrl-c/break

1 The user presses the first key

255 An error condition on the command line was detected

The position of the valid character pressed by the other user in the list


defrag

0 Fragment compression was successful

1 An internal error has occurred

2 There are no empty clusters on the disk. To run DEFRAG, there must be at least one empty cluster

3 The user exited DEFRAG with Ctrl-C

4 A general error occurred

5 DEFRAG encountered an error reading the cluster

6 DEFRAG encountered an error writing the cluster

7 There is something wrong with allocating space

8 Memory error

9 There is not enough space to compress disk fragmentation


deltree

0 Successfully deleted a directory


diskcomp

0 Two sets are the same

1 Found different

2 The comparison was terminated by CTRL-C

3 A critical error has occurred

4 An initialization error has occurred


find

0 The lookup was successful and at least one matching string was found

1 The search was successful but no matching string was found

2 There was an error in the lookup


keyb

0 The keyboard definition file was successfully loaded

1 Use illegal keyboard code, character sets, or syntax

2 Keyboard definition file is bad or not found

4 There was an error communicating with the keyboard and monitor

5 The required character set is not ready


move

0 The specified file was successfully moved

1 An error has occurred


msav /N

86 The virus was detected


replace

0 REPLACE successfully replaced or joined the file

1 MS-DOS version is not compatible with REPPLACE

2 REPLACE could not find the source file

3 REPLACE could not find the source or destination path

5 You cannot access the file you want to replace

8 There is not enough memory to execute REPPLACE

11 Command line synth error


restore

0 RESTORE successfully recovered the file

1 RESTORE could not find the file to recover

3 The user terminates the recovery process by CTRL-C

4 RESTORE was terminated due to an error


scandisk

0 ScanDisk did not detect any errors on the drive it was checking

1 ScanDisk cannot be run because of the wrong syntax on the command line

2 ScanDisk terminates unexpectedly due to memory exhaustion or an internal error

3 The user let ScanDisk exit midway through

4 When scanning, the user decides to exit early

254 ScanDisk found a disk failure and has been fully corrected

255 ScanDisk found a disk failure, but it could not be fully corrected


setver

0 SETVER successfully completed the task

1 The user specifies an invalid command switch

2 The user specified an illegal file name

3 There is not enough system memory to run the command

4 The user specifies an illegal version number format

5 SETVER did not find the specified item in the version table

6 SETVER did not find the SETVER .EXE file

7 The user specified an illegal drive

8 The user specifies too many command line parameters

9 SETVER detected the loss of command line parameters

10 When reading the SETVER .EXE file, SETVER detected an error

11 SETVER. The EXE file is corrupt

12 The specified SETVER .EXE does not support version tables

13 There is not enough space in the version table for new items

14 AN error was detected .EXE when writing the SETVER file

========================================================================


3、IF STRING1 == STRING2


Establish the TEST5 .BAT, which reads as follows:

@echo off

IF "%1" == "A" FORMAT A:


Perform:

C:\>TEST5 A

On the screen, the contents of whether to format the A:disk appear.


Note: To prevent parameters from being empty, strings are generally enclosed in double quotes (or other symbols, note that reserved symbols cannot be used).

e.g.: if .%1.


5、GOTO


Establish the TEST6 .BAT, the document reads as follows:

@ECHO OFF

IF EXIST C:\AUTOEXEC. B AT GOTO _COPY

GOTO _DONE

:_COPY

COPY C:\AUTOEXEC. B AT D:\

:_DONE


Attention:

(1) Before the mark is the colon of the ASCII character": ", there can be no space between the colon and the marker.

(2) The naming rules for labels are the same as between file names.

(3) THE DOS supports a label of up to eight characters and jumps to the nearest label when it is not possible to distinguish between the two markers.


The willsort comment is noted

1) Label is also known as label

2) Labels cannot start with most non-alphanumeric characters, and many can be used in file names

3) When it is not possible to distinguish between two labels, jumps to the label at the top of the position

========================================================================


6、FOR


Establish C: .TEST7. B AT, the file reads:

@ECHO OFF

FOR %%C IN (*. B AT *. T XT *. S YS) DO TYPE %%C


Run:

C:\>TEST7


After execution, all file contents with BAT, TXT, SYS extensions in the C:root directory are displayed on the screen (excluding hidden files).