───────────────── Moderator's Note ─────────────────
Click here to visit the latest updated version of this article
Click here to download the latest updated archive of this article (plain text format)
───────────────── Moderator's Note ─────────────────
The original author wrote with very little professional rigor; the article is simply full of errors, and long-winded besides. If it were not revised and improved, it would really mislead learners. Therefore, on the basis of the original, I revised it and corrected most of the errors (of course, new errors may inevitably have been introduced as well; I hope experts will point them out promptly when they find them).
URL: http://www.txwm.com/News/technic/200408/2004081609515074304.html
Excerpted from: Tianxia Internet Café Alliance Author: Anonymous
Revised and improved by: Climbing(xclimbing@msn.com)
Last revision date: August 19, 2004
Introduction to batch files
Files with the extension bat (under nt/2000/xp/2003 they can also be cmd) are batch files.
First of all, a batch file is a text file. Each line in this file is a DOS command (most of the time, just like the command lines we execute at the DOS prompt). You can use Edit under DOS or any text file editing tool such as Windows Notepad (notepad) to create and modify batch files.
Second, a batch file is a simple program. It can use conditional statements (if) and flow control statements (goto) to control the flow of command execution, and in batch files you can also use loop statements (for) to execute a command repeatedly. Of course, the programming ability of batch files is very limited compared with programming languages such as C, and it is also quite non-standard. The program statements in batch files are simply DOS commands one by one (including internal commands and external commands), and the capabilities of batch files mainly depend on the commands you use.
Third, every completed batch file is equivalent to a DOS external command. You can put the directory where it is located into your DOS search path (path) so that it can be run from any location. A good habit is to create a bat or batch directory on the hard disk (for example C:\BATCH), then put all the batch files you write into that directory. That way, as long as you set c:\batch in path, you can run all the batch programs you wrote from any location.
Fourth, under DOS and Win9x/Me systems, the AUTOEXEC.BAT batch file in the root directory of drive C: is an auto-run batch file. It runs automatically every time the system starts. You can put commands that need to run every time the system starts into this file, such as setting the search path, loading the mouse driver and disk cache, setting system environment variables, and so on. Below is an example of an autoexec.bat running under 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 role of batch files
Simply put, the role of batch files is to automatically execute multiple commands in succession.
Here, let me first talk about the simplest application: when starting the WPS software, each time you must execute (content before > indicates the DOS prompt):
C:\>cd wps
C:\WPS>spdos
C:\WPS>py
C:\WPS>wbx
C:\WPS>wps
If you have to execute all this every time before using WPS, don't you find it troublesome?
Alright, with a batch file, these troublesome operations can be simplified. First we write a runwps.bat batch file with the following contents:
@echo off
c:
cd\wps
spdos
py
wbx
wps
cd\
After that, whenever we want to enter WPS, we only need to run the batch file runwps.
Commonly used commands
echo, @, call, pause, rem (small trick: use :: instead of rem) are several of the most commonly used commands in batch files, so let's start learning from them.
echo means to display the characters after this command
echo off means that after this statement, all commands that run will not display the command line itself
@ is similar to echo off, but it is added at the very beginning of each command line, indicating that when it runs, that line's command line itself is not displayed (it only affects the current line).
call calls another batch file (if you do not use call and directly call another batch file, then after that batch file finishes executing, it will not be able to return to the current file and continue executing the subsequent commands in the current file).
pause running this statement will pause execution of the batch file and display the prompt Press any key to continue... on the screen, waiting for the user to press any key before continuing
rem means that the characters after this command are comment lines (annotations), which are not executed and are only for your own future reference (equivalent to comments in a program).
Example 1: Use edit to edit a.bat, enter the following content, save it as c:\a.bat, and after executing the batch file it can do the following: write all files in the root directory into a.txt, start UCDOS, enter WPS, and so on.
The contents of the batch file are: Command comments:
@echo off Do not display subsequent command lines or the current command line
dir c:\*.* >a.txt Write the list of files on drive C into a.txt
call c:\ucdos\ucdos.bat Call ucdos
echo 你好 Display "你好"
pause Pause, wait for a keypress to continue
rem 准备运行wps Comment: prepare to run wps
cd ucdos Enter the ucdos directory
wps Run wps
Parameters of batch files
Batch files can also use parameters like functions in C (equivalent to command-line parameters of DOS commands), and this requires the parameter marker “%”.
% indicates parameters. Parameters refer to strings added after the batch filename when running the batch file, separated by spaces (or Tabs). Variables can range from %0 to %9. %0 represents the batch command itself, and the other parameter strings are represented in order by %1 through %9.
Example 2: There is a batch file in the root directory of C: named f.bat, with the following contents:
@echo off
format %1
If you execute C:\>f a:
then when f.bat is executed, %1 means a:, so format %1 is equivalent to format a:, and therefore what the above command actually executes when run is format a:
Example 3: There is a batch file in the root directory of C: named t.bat, with the following contents:
@echo off
type %1
type %2
Then run C:\>t a.txt b.txt
%1 : means a.txt
%2 : means b.txt
So the above command will display the contents of files a.txt and b.txt in sequence.
Special commands
if goto choice for are relatively advanced commands in batch files. If you use these very skillfully, then you are a batch file expert.
1. if is a conditional statement, used to determine whether specified conditions are met, and then decide which different command to execute. There are three formats:
1、if "parameter" == "string" command to execute
If the parameter is equal to (not means not equal, same below) the specified string, the condition is true and the command runs; otherwise the next statement runs.
Example: if "%1"=="a" format a:
2、if exist filename command to execute
If the specified file exists, the condition is true and the command runs; otherwise the next statement runs.
For example: if exist c:\config.sys type c:\config.sys
This means that if the file c:\config.sys exists, then display its contents.
3、if errorlevel <number> command to execute
Many DOS programs return a numeric value after finishing execution to indicate the result (or status) of the program run. With the if errorlevel command you can judge the program's return value, and according to different return values decide which different command to execute (the return values must be arranged in descending order). If the return value equals the specified number, the condition is true and the command runs; otherwise the next statement runs.
For example if errorlevel 2 goto x2
2. goto when the batch file runs to this point, it jumps to the label specified by goto (a label is defined as : followed by a standard string). The goto statement is generally used together with if, to execute different command groups according to different conditions.
For example:
goto end
:end
echo this is the end
A label is defined with “:string”, and the line containing the label is not executed.
3. choice with this command, the user can input a character (for selection), so that according to the user's choice, a different errorlevel is returned, and then together with if errorlevel, different commands are run based on the user's choice.
Note: the choice command is an external command provided by DOS or Windows systems. The syntax of the choice command differs slightly in different versions; please use choice /? to see its usage.
The syntax of the choice command (this syntax is for the choice command in Windows 2003; the syntax of the choice command in other versions is mostly similar):
CHOICE
Description:
This tool allows users to select one item from a list of choices and returns the index of the selected item.
Parameter list:
/C choices Specifies the list of choices to create. The default list is "YN".
/N Hides the list of choices in the prompt. The message before the prompt
is still displayed, and the choices remain enabled.
/CS Allows case-sensitive choices. By default, this tool
is not case-sensitive.
/T timeout The number of seconds to pause before making the default choice. Acceptable values are from 0
to 9999. If 0 is specified, there will be no pause and the default choice
will be selected.
/D choice Specifies the default choice after nnnn seconds. The character must be in the set of choices
specified by the /C option; at the same time, nnnn must be specified with /T.
/M text Specifies the message to display before the prompt. If omitted, the tool only
displays the prompt.
/? Displays help information.
Notes:
The ERRORLEVEL environment variable is set to the index of the key selected from the choice set. The first listed
choice returns 1, the second choice returns 2, and so on. If the user presses a key that is not a valid choice,
the tool emits a warning beep. If the tool detects an error condition, it returns an ERRORLEVEL
value of 255. If the user presses Ctrl+Break or Ctrl+C, the tool returns an ERRORLEVEL
value of 0. When using the ERRORLEVEL parameter in a batch program, arrange the parameters in
descending order.
Examples:
CHOICE /?
CHOICE /C YNC /M "To confirm press Y, for no press N, or to cancel press C."
CHOICE /T 10 /C ync /CS /D y
CHOICE /C ab /M "For option 1 please select a, for option 2 please select b."
CHOICE /C ab /N /M "For option 1 please select a, for option 2 please select b."
If I run the command: CHOICE /C YNC /M "To confirm press Y, for no press N, or to cancel press C."
the screen will display:
To confirm press Y, for no press N, or to cancel press C. ?
Example: the contents of test.bat are as follows (note: when using if errorlevel to judge return values, they should be arranged from high to low):
@echo off
choice /C dme /M "defrag,mem,end"
if errorlevel 3 goto end
if errorlevel 2 goto mem
if errotlevel 1 goto defrag
:defrag
c:\dos\defrag
goto end
:mem
mem
goto end
:end
echo good bye
After this batch file runs, it will display “defrag,mem,end?”; the user may choose d m e, and then the if statements will judge according to the user's choice. d means execute the program section labeled defrag, m means execute the program section labeled mem, and e means execute the program section labeled end. At the end of each program section, goto end jumps the program to the label end, then the program will display good bye, and the batch file run ends.
4. for loop command: as long as the conditions are met, it will execute the same command multiple times.
Syntax:
Execute a specific command for each file in a set of files.
FOR %%variable IN (set) DO command
%%variable Specifies a replaceable single-letter parameter.
(set) Specifies one file or a set of files. Wildcards may be used.
command Specifies the command to execute for each file.
command-parameters
Specifies parameters or command-line switches for the specific command.
For example, if a batch file contains a line:
for %%c in (*.bat *.txt) do type %%c
then this command line will display the contents of all files in the current directory whose extensions are bat and txt.
Batch file examples
1. IF-EXIST
1)
First use Notepad to create a batch file test1.bat in C:\, with the following contents:
@echo off
IF EXIST \AUTOEXEC.BAT TYPE \AUTOEXEC.BAT
IF NOT EXIST \AUTOEXEC.BAT ECHO \AUTOEXEC.BAT does not exist
Then run it:
C:\>TEST1.BAT
If AUTOEXEC.BAT exists in C:\, then its contents will be displayed; if it does not exist, the batch file will tell you that the file does not exist.
2)
Next create another file test2.bat with the following contents:
@ECHO OFF
IF EXIST \%1 TYPE \%1
IF NOT EXIST \%1 ECHO \%1 does not exist
Execute:
C:\>TEST2 AUTOEXEC.BAT
The result of running this command is the same as above.
Explanation:
(1) IF EXIST is used to test whether a file exists. The format is
IF EXIST command
(2) %1 in the file test2.bat is a parameter. DOS allows 9 batch parameter values to be passed to a batch file, namely %1~%9 (%0 represents the test2 command itself). This is somewhat like the relationship between actual parameters and formal parameters in programming: %1 is the formal parameter, and AUTOEXEC.BAT is the actual parameter.
3) Going one step further, create a file named TEST3.BAT with the following contents:
@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
the screen will display:
XIAO
TIAN
XIN
If you run:
C:\>TEST3 A B
the screen will display
XIAO
TIAN
During execution of this command, DOS will assign an empty string to parameter %3.
2、IF-ERRORLEVEL
Create TEST4.BAT with the following contents:
@ECHO OFF
XCOPY C:\AUTOEXEC.BAT D:\
IF ERRORLEVEL 1 ECHO File copy failed
IF ERRORLEVEL 0 ECHO File copied successfully
Then execute the file:
C:\>TEST4
If the file is copied successfully, the screen will display “File copied successfully”; otherwise it will display “File copy failed”.
IF ERRORLEVEL is used to test the return value of the previous DOS command. Note that it is only the return value of the previous command, and the return values must be judged in descending order.
Therefore, the following batch file is wrong:
@ECHO OFF
XCOPY C:\AUTOEXEC.BAT D:\
IF ERRORLEVEL 0 ECHO File copied successfully
IF ERRORLEVEL 1 ECHO Source file not found
IF ERRORLEVEL 2 ECHO The user aborted the copy operation with ctrl-c
IF ERRORLEVEL 3 ECHO A preset error prevented the file copy operation
IF ERRORLEVEL 4 ECHO Disk write error during copy
Whether the copy succeeds or not, the following:
Source file not found
The user aborted the copy operation with ctrl-c
A preset error prevented the file copy operation
Disk write error during copy
will all be displayed.
Below are the return values of several commonly used commands and what they mean:
backup
0 Backup successful
1 Backup file not found
2 File sharing conflict prevented backup from completing
3 User aborted backup with ctrl-c
4 Backup operation aborted due to a fatal error
diskcomp
0 Disks are identical
1 Disks are different
2 User aborted comparison with ctrl-c
3 Comparison operation aborted due to a fatal error
4 Preset error aborted comparison
diskcopy
0 Disk copy operation successful
1 Non-fatal disk read/write error
2 User ended copy operation with ctrl-c
3 Disk copy aborted due to a fatal processing error
4 Preset error prevented copy operation
format
0 Format successful
3 User aborted formatting with ctrl-c
4 Formatting aborted due to a fatal processing error
5 At the prompt “proceed with format(y/n)?” the user entered n to end
xcopy
0 File copied successfully
1 Source file not found
2 User aborted copy operation with ctrl-c
4 Preset error prevented file copy operation
5 Disk write error during copy
3、IF STRING1 == STRING2
Create TEST5.BAT, with the following contents:
@echo off
IF "%1" == "A" FORMAT A:
Execute:
C:\>TEST5 A
The screen will then show the prompt asking whether to format drive A:.
Note: to prevent the parameter from being empty, the string is generally enclosed in double quotation marks (or other symbols; note that reserved symbols cannot be used).
For example: if == or if %1*==A*
5、GOTO
Create TEST6.BAT, with the following contents:
@ECHO OFF
IF EXIST C:\AUTOEXEC.BAT GOTO _COPY
GOTO _DONE
:_COPY
COPY C:\AUTOEXEC.BAT D:\
:_DONE
Notes:
(1) Before the label is the ASCII colon character ":"; there must be no spaces between the colon and the label.
(2) The naming rules for labels are the same as the naming rules for filenames.
(3) DOS supports labels up to eight characters long. When it cannot distinguish between two labels, it will jump to the nearest one.
6、FOR
Create C:\TEST7.BAT, with the following contents:
@ECHO OFF
FOR %%C IN (*.BAT *.TXT *.SYS) DO TYPE %%C
Run:
C:\>TEST7
After execution, the screen will display the contents of all files in the root directory of drive C: whose extensions are BAT, TXT, and SYS (excluding hidden files).

DigestI






