中国DOS联盟论坛

China DOS Union

-- Unite DOS · Advance DOS · Grow DOS --
Union site: www.cn-dos.net Forum site: www.cn-dos.net/forum
Guest | Log in | Register | Members | Search | China DOS Union
中国DOS联盟论坛
The time now is 2026-08-13 19:30
47,811 topics / 349,897 posts / today 0 new / 48,256 members
DOS学习入门 & 精彩文章 (教学室) » How to make a batch file
Printable Version  1,413 / 9
Floor1 zwq2009 Posted 2004-04-10 00:00
初级用户 Posts 5 Credits 118
Is there any expert who knows about tutorials on making batch files?
Floor2 老汉 Posted 2004-04-11 00:00
初级用户 Posts 2 Credits 110
Go ask Kinglion.
Floor3 wphs0326 Posted 2004-04-11 00:00
银牌会员 Posts 509 Credits 1,708 From 安徽淮南
Batch files are files with the extension.BAT composed of one or more DOS commands and executable commands. When the user uses the batch file name as a command, DOS will automatically execute the commands in the file in sequence one by one. The characteristic of batch files is that they can be established once and executed multiple times.

There is a special batch file in batch files. Every time the computer starts, the system automatically executes each command in this file. This file must meet two conditions: first, the file name is AUTOEXEC.BAT, and second, the location of this file must be in the root directory of the boot disk (also known as the system disk).

In addition to using DOS commands in batch files, batch subcommands can also be used. These commands can also be regarded as internal commands of DOS. They are:

1) ECHO - Display mode setting; where ECHO ON makes subsequent commands display before execution, ECHO OFF makes subsequent commands not display before execution, and ECHO MESSAGE displays the information specified by MESSAGE regardless of the state of ECHO being ON or OFF.
2) REM - Comment command.
3) PAUSE - Pause the system processing. The system displays "Press any key to continue…" and waits for the user to press any key to continue execution.
4) GOTO - Transfer subcommand.
5) IF - Conditional subcommand.
6) FOR - Loop subcommand.
7) SHIFT - Change the position of parameters.

The computer looks for the autoexec.bat batch file every time it starts, so that some commands that need to be executed every time the computer starts can be executed, such as setting the path path, loading the mouse driver mouse, disk acceleration smartdrv, etc., which can make your computer truly automated.

echo, @, call, pause, rem are several of the most commonly used commands in batch files. We start learning from them. echo means to display the characters after this command. echo off means that all running commands after this statement do not display the command line itself. @ is similar to echo off, but it is added at the front of other command lines, indicating that the command line itself is not displayed during execution. call calls another batch file (if you directly call another batch file, you will not be able to execute the subsequent commands of the current file after executing that file). pause running this sentence will pause, display "Press any key to continue...", and wait for the user to press any key to continue. rem means that the characters after this command are explanation lines, which are not executed, just for future reference by yourself.

Example: Use edit to edit the a.bat file, enter the following content and save it as c:\a.bat. After executing this batch file, the functions of writing all files in the root directory into a.txt, starting UCDOS, entering WPS, etc. can be realized.

The content of the batch file is:
echo off             Do not display the command line
dir c:\*.* >a.txt        Write the file list of drive C into a.txt
call c:\ucdos\ucdos.bat    Call ucdos
echo Hello           Display "Hello"
pause             Pause, wait for the key to continue
rem Use WPS          Comment that WPS will be used
cd ucdos           Enter the ucdos directory
wps             Use WPS

Parameters can also be used in batch files like in the C language, which only requires using a parameter identifier %.
% represents a parameter, and the parameter refers to the string added after the file name when running the batch file. Variables can range from %0 to %9, %0 represents the file name itself, and the strings are represented in sequence by %1 to %9.

For example, a batch file in the root directory of drive C is named f.bat, and the content is format %1. Then if you execute C:\>f a:, the actual execution is format a:.
Another example: A batch file in the root directory of drive C is named t.bat, and the content is type %1 type %2. Then running C:\>t a.txt b.txt will sequentially display the contents of the a.txt and b.txt files.

if, goto, choice, for are relatively advanced commands in batch files. If you are proficient in using these, you are an expert in batch files. if means to judge whether the specified condition is met, so as to decide to execute different commands. There are three formats:
1. if "parameter" == "string"  Command to be executed
If the parameter is equal to the specified string, the condition is established, and the command is run; otherwise, the next sentence is run. (Note that there are two equal signs). For example, if "%1"=="a" format a:
2. if exist file name  Command to be executed
If the specified file exists, the condition is established, and the command is run; otherwise, the next sentence is run. For example, if exist config.sys edit config.sys
3. if errorlevel number  Command to be executed
If the return code is equal to the specified number, the condition is established, and the command is run; otherwise, the next sentence is run. For example, if errorlevel 2 goto x2. All DOS programs will return a number to DOS when running, called the error code errorlevel or return code.

goto The batch file will jump to the label specified by goto when running here. Generally, it is used in conjunction with if. For example:
goto end

:end
echo this is the end

The label is represented by :string, and the line where the label is located is not executed.

choice Using this command can let the user enter a character, so as to run different commands. When using it, the /c: parameter should be added. After c:, the characters that can be entered should be written, and there are no spaces between them. Its return code is 1234...

For example: choice /c:dme defrag,mem,end
It will display
defrag,mem,end?

For example, the content of test.bat is as follows:
@echo off
choice /c:dme defrag,mem,end
if errorlevel 3 goto defrag should first judge the highest numerical error code
if errorlevel 2 goto mem
if errotlevel 1 goto end

:defrag
c:\dos\defrag
goto end

:mem
mem
goto end

:end
echo good bye

After this file is run, it will display defrag,mem,end? The user can choose d, m, e, and then the if statement will make a judgment. d means executing the program segment labeled defrag, m means executing the program segment labeled mem, e means executing the program segment labeled end. Each program segment finally uses goto end to jump the program to the end label, and then the program will display good bye, and the file ends.

The for loop command will execute the same command multiple times as long as the condition is met.
Format FOR in (collection) DO
As long as the parameter f is within the specified collection, the condition is established, and the command is executed.

If there is a line in a batch file:
for %%c in (*.bat *.txt) do type %%c
The meaning is that if the file ends with bat or txt, the content of the file is displayed.

DOS will automatically run the autoexec.bat file when starting. Generally, we load the programs that are used every time in it, such as: path (set path), smartdrv (disk acceleration), mouse (mouse startup), mscdex (CD-ROM connection), doskey (keyboard management), set (set environment variables), etc.

If this file is not in the root directory of the boot disk, the computer will let the user enter the date and time.

For example, a typical autoexec.bat content is as follows:

@echo off                     Do not display the command line
prompt $p$g                   Set the prompt to have a directory prompt before
path c:\dos;c:\;c:\windows;c:\ucdos;c:\tools   Set the path
lh c:\dos\doskey.com              Load keyboard management
lh c:\mouse\mouse.com            Load mouse management
lh c:\dos\smartdrv.exe           Load disk acceleration management
lh c:\dos\mscdex /S /D:MSCD000 /M:12 /V   Load CD-ROM driver
set temp=c:\temp              Set the temporary directory
Floor4 wphs0326 Posted 2004-04-11 00:00
银牌会员 Posts 509 Credits 1,708 From 安徽淮南
### (I) Applying DOS Redirection Function

The standard input and output in DOS are usually carried out on the standard devices keyboard and display. By using redirection, the input and output can be conveniently redirected to disk files or other devices. For example, during the execution of a batch command to prohibit the output information from disturbing the screen after the command or program is executed, the DOS redirection function can be used to redirect the output to the NUL device (NUL does not point to any actual device): C:\>COPY A.TXT B.TXT > NUL.

The information "1 file(s) copied" will not be displayed after the command is executed. Some interactive programs require a lot of keyboard input when executing, but sometimes the input is fixed. To speed up the running speed, an input file can be established in advance. The content of this file is the keyboard input items of the program, and each input item occupies one line. Suppose there is a program ZB, and all its input items are included in the file IN.DAT. Executing C:\>ZB NUL will automatically execute the program.

### (II) Applying DOS Pipe Function

The pipe function of DOS makes the standard output of one program or command be used as the standard input of another program or command. For example, write the input command of DEBUG into a file AAA, and use the TYPE command to transfer the content of AAA to DEBUG through the pipe function. During the execution of DEBUG, it will no longer obtain command parameters from the console, thereby improving the machine efficiency. The command is: C:\>TYPE AAA|DEBUG >BBB.

### (III) Subroutine

A CALL command can be used in a batch file to call another sub-batch file. When the sub-batch file is executed and ends, it will automatically return to the parent batch file and continue to execute downward. For example: A.BAT B.BAT, where A calls B. The content of A.BAT is as follows:

@ECHO OFF
CALL B
CD \BASIC
BASICA BG
@ECHO ON

### (IV) Menu Selection Function

The one-byte return code provided by the DOS function calls 31H or 4CH can be used to process the return code through the batch sub-commands IF and ERRORLEVEL, which can achieve the purpose of automatically executing a batch of commands. The menu prompt function of all high-level languages can be realized in the batch file, making the batch file more flexible and convenient. First, use DEBUG to create a menu-driven program MENU.COM, and correspondingly write a batch file LG.BAT. The specific content and method are shown in the following table:

DEBUG
-A
-166C:0100 MOV DX,111
-166C:0103 MOV AH,09
-166C:0105 INT 21
-166C:0107 MOV AH,01
-166C:0109 INT 21
-166C:010B MOV AH,4C
-166C:010D INT 21
-166C:010F INT 20
-166C:0111 DB '******************************'0D 0A
-166C:0131 DB '* 1.Turbo Pascal 5.00 *'0D 0A
-166C:0151 DB '* 2.Turbo Basci 1.00 *'0D 0A
-166C:0171 DB '* 3.Turbo Prolog 2.00 *'0D 0A
-166C:0191 DB '* 4.Turbo C 2.00 *'0D 0A
-166C:01B1 DB '* 0.Exit *'0D 0A
-166C:01B1 DB '******************************'0D 0A
-166C:01F1 DB 'Your choice(0..4) : '24 0D 0A 1A
-166C:0209
-R CX
CX 0000
:108
-N MENU.COM
-W
Writing 0108 bytes
-Q
@ECHO OFF:
START
CLS
MENU
IF ERRORLEVEL 52 GOTO C
IF ERRORLEVEL 51 GOTO PRO
IF ERRORLEVEL 50 GOTO BAS
IF ERRORLEVEL 49 GOTO PAS
IF ERRORLEVEL 48 GOTO EX
CLS
GOTO START
AS
CD \TP5.00
TURBO
CD \
GOTO START
:BAS
CD \TB
TB
CD \
GOTO START
RO
CD \TPROLOG
PROLOG
CD \
GOTO START
:C
CD \TURBOC
TC
CD \
GOTO START
:EX
@ECHO ON

When executing LG, a menu will appear in the upper left corner of the screen and prompt the user to enter a choice. When the selected function is executed and ends, it will return to the main menu to request a choice again until the "0" function is selected, and the program will end and return to DOS.

### (V) Using the Command Processor to Complete a Large Number of Repetitive Tasks

DOS provides a method to call secondary command programs, which can realize the function equivalent to subroutines and is very useful under DOS versions before MS DOS3.3. For example, if you have a batch of FORTRAN source programs that need to be compiled, first write two batch files MAKEOBJ.BAT and C.BAT, and then execute MAKEOBJ, which can compile all FORTRAN source programs with the extension.FOR in the current directory into OBJ files. This method is fast and correct, with less human-computer interaction, and reduces a lot of labor for programmers.

MAKEOBJ.BAT C.BAT
@ECHO OFF
ECHO COMPILE FORTRAN PROGRAMS.
FOR %%A IN (*.FOR) DO COMMAND /C C %%A
ECHO FINISH !
@ECHO ON @ECHO OFF
ECHO ------ COMPILE %1 ------
FOR1 %1; >NUL
FOR2 >NUL
@ECHO ON
Floor5 wphs0326 Posted 2004-04-11 00:00
银牌会员 Posts 509 Credits 1,708 From 安徽淮南
### Batch File Application Tips
Although Windows 3.x and Windows 95 are increasingly widely used, DOS is still favored by many users. As for DOS batch files, many users do not give full play to their due role in practical applications. This article discusses several tips on the application of DOS batch files for readers' reference.

#### 1. Display Selected DIR Information
The DIR command in DOS provides the functions of switches and wildcards to facilitate users to display special types of files in a directory. However, the DIR command also has many unsatisfactory aspects. For example, if we want to display files other than those with the .TXT extension in a directory, the DIR command is powerless. The solution is to use the FIND command to achieve this function:

```
DIR /A-D | FIND/V "TXT"
```

The "/A-D" switch tells the DIR command not to display directories. The pipe command "|" specifies that the listed directories are displayed according to the execution result of the FIND command. The /V switch tells the FIND command to list all lines that do not include the string in double quotes. The string in double quotes should be preceded by a space (the space is to prevent the FIND command from excluding files whose base filenames include the string TXT, such as NEWTXT.DOC, so the space is indispensable here). In fact, the FIND command can appear multiple times in one line of command. For example, to display all files in a directory that do not include the .TXT and .DOC extensions, the command is as follows:

```
DIR /A-D | FIND/V "TXT" | FIND/V "DOC"
```

Next, we give an example using the above skills. This example is used to display all files except the specified extensions. Here, it is assumed that the file name is NEWDIR, and the command format is:

```
NEWDIR
```

Among them, the files with extensions extension1 and extension2 are the ones that the user does not want to display.

```
@ECHO OFF
IF "%1"=="" GOTO NOPARAM
SET EXTENSION1=%1
SET EXTENSION2=%2
IF "%2"=="" SET EXTENSION2=.
DIR /A-D | FIND /V /I "%EXTENSION1%" | FIND /V /I "%EXTENSION2%" | MORE
GOTO END

:NOPARAM
ECHO No file extension specified. Syntax
ECHO is:
ECHO.
ECHO NEWDIR
ECHO.

:END
SET EXTENSION1=
SET EXTENSION2=
```

It is worth noting that a switch /I is added after the FIND command. The function of this switch is to make the FIND command ignore the case of the extension typed in the command line.

#### 2. Automate Input
When we write batch files, sometimes we need to specify the date in the file. Generally speaking, we add the DATE command in the batch file, so the program will prompt the user to enter the date during operation. Here we give a method to add a carriage return after the DATE command:

```
ECHO. | DATE
```

ECHO. is used to send a carriage return to the screen, and the pipe symbol is used to redirect the carriage return to the DATE command. To not display the prompt of the DATE command, you can use the following command:

```
ECHO. | DATE | FIND "Current"
```

If you want to add a line of date in a text file, you can use the following command:

```
ECHO. | DATE | FIND "Current" >THISDATE.TXT
```

This method is also suitable for the TIME command and FORMAT command of DOS.

#### 3. Shield Display Information
In batch files, the combination of "ECHO" and "|" is very useful. This combination can sometimes eliminate the display information we do not want to see. For example, to delete all files in a directory but not let the system display "Are you sure(Y/N)", you can use the following command:

```
ECHO Y | DEL *.* >NUL
```

In practical applications, we can reasonably combine ECHO and the pipe symbol to make the content displayed on the screen meet our requirements.

#### 4. Set or Reset Path
With the increase of application systems, some applications require users to add their directories to the PATH statement. However, the number of characters supported by PATH cannot exceed 127 characters, so it may sometimes be restricted in specific applications. Here we explore the solution through an example. Suppose the path we set is:

```
PATH=C:\DOS;C:\UTILS;C:\BAT
```

And at this time we need to run a word processing software and need to set the path to:

```
PATH=C:\DOS;C:\UTILS;C:\BAT;C:\TEXTEDIT
```

After running the above word processing software, we also need to set the path back to the original one. Here we can complete it through the following batch program:

```
@ECHO OFF
SET OLDPATH=%PATH%
PATH %PATH%;C:\TEXTEDIT
CD C:\TEXTEDIT
TEXTEDIT
SET PATH=%OLDPATH%
SET OLDPATH=
CD C:\
```

The second line of the batch program saves the current path in the environment variable OLDPATH; the third line combines the paths; the sixth line after the system runs, DOS hands over the control to the batch program, and at this time sets the path back to the original path. Through this method, we can solve the above problem.

#### 5. Reasonably Use REM, ::, and GOTO
The function of the REM statement in batch files is well known, but in specific applications, :: and GOTO can be used instead of the REM statement. For example:

```
ECHO The following lines are remarks that will not be display
::This line will not be display
::Neither will this line
ECHO the batch file proceeds
```

The same function can be realized using the GOTO statement:

```
ECHO The following lines are remarks that will not be display
GOTO JUMP
This line will not be display
Neither will this line
:JUMP
ECHO The batch file proceeds
```

Generally speaking, reasonably using REM, ::, and GOTO will improve the efficiency of using batch files. Usually, when the comment is short, use :: or GOTO; when the comment is long, use REM. Because the execution time of REM has nothing to do with the length of the comment, while the execution time of :: and GOTO will double when the comment is long.

#### 6. Convert User Input to Uppercase
People who write batch files know that the IF statement is case-sensitive for uppercase and lowercase letters. For example:

```
IF "%1"=="ERASE" GOTO ERASE
```

If the user types erase or Erase or any combination of uppercase and lowercase of these five letters, DOS will think that the condition of the IF statement is not satisfied, and then not execute the GOTO statement. The solution to this problem is to use the PATH command to convert the user's input lowercase letters to uppercase. The program is as follows:

```
SET OLDPATH=%PATH%
SET PATH=%1
SET USERINPUT=%PATH%
SET PATH=%OLDPATH%
IF %USERINPUT%==ERASE GOTO ERASE
SET OLDPATH=
```

The first line stores the current path in the environment variable OLDPATH. The second line sets the PATH variable to the user's input and converts the input content to uppercase. The third line sets an environment variable to PATH (that is, the user's input content). The fourth line restores the original content of PATH. The fifth line uses the converted string in the IF statement. The last line clears the OLDPATH environment variable.

#### 7. FOR...IN...DO Loop
The limitation of FOR...IN...DO is revealed when one or more commands need to be executed at a time. For example, in a batch file, we cannot simply display each file in a directory through the MORE command and then selectively delete them. The following example demonstrates the method to overcome the above problem:

```
@ECHO OFF
IF "%1"==":TASKS:" GOTO TASKS
FOR %%A IN (%1) DO CALL %0 :TASKS: %%A
GOTO END

:TASKS
CLS
MORE %2
DEL /P %2

:END
```

Here we name this batch program LOOPER. If we want to display all text files and then give a deletion option, we can type:

```
LOOPER *.TXT
```

In the first execution, the IF statement in the second line checks whether %1 contains :TASKS:; because %1 does not contain :TASKS: this time, the program runs the FOR statement. In this example, the program first takes out the first file with the .TXT extension and then executes the CALL command. Suppose the first text file is ABC.TXT, then DOS executes the following command:

```
CALL LOOPER :TASKS: ABC.TXT
```

That is, LOOPER runs its second copy with two parameters (:TASKS: and ABC.TXT). When LOOPER runs for the second time, it checks again whether %1 contains the value :TASKS:, and this time the condition is satisfied. LOOPER executes the program segment below :TASKS:. MORE displays the content of ABC.TXT, and then DEL /P displays the option of whether to delete the file. When the :TASKS: routine is executed, DOS closes the second LOOPER and returns to the FOR ...IN ...DO statement of the first LOOPER to process the next .TXT file.

#### 8. Hide Command Display
Many DOS commands display their results, but sometimes these results displayed on the screen will make users confused. For example, COPY FILE1.TXT FILE2.TXT will display "1 file(s) copied" on the screen. If we do not want the system to display this information, we can use the following method:

```
COPY FILE1.TXT FILE2.TXT >NUL
```

This method is also suitable for the PAUSE command in batch files to shield the display information "Press any key to continue". For example:

```
@ECHO OFF
ECHO There is no disk in drive A, Insert a
ECHO disk and press Enter.
PAUSE >NUL

```

### Subroutines in Batch Commands
Most mature high-level programming languages allow you to build commonly used routines into independent modules, that is, subroutines. It retains the independence of the code, makes the program modular, and is convenient for organization. At least it can be said that DOS batch commands do not fully support subroutines, but you can call subroutines with the GOTO command at any time.

Usually, the label used by the GOTO command can also accept the label stored in the environment variable. For example:

```
SET LABELNAME=START
GOTO %LABELNAME%
```

By replacing the label at the beginning of the subroutine and setting the GOTO %RETURN% statement at the end of the subroutine, you can build subroutines in DOS batch commands. As long as you SET an environment variable RETURN, you can call subroutines at any place in the batch command. For example, you can assign a value to the label and call the subroutine in the next line, and then the GOTO statement jumps to the beginning of the subroutine. The program structure is as follows:

```
REM This set the environment
REM variable and calls the
REM subroutine
SET RETURN=HERE
GOTO SUB
HERE
SUB
REM
Place subroutine statements
REM below
GOYO %RETURN%
```

The statement GOTO SUB is transferred to the subroutine SUB, and you can execute any statements in SUB. When executing to GOTO %RETURN%, the batch command returns control to the label HERE, because the environment variable RETURN is reassigned to HERE. If you use a unique label (such as RETURN) each time you call SUB, you can call SUB multiple times in multiple places.
Floor6 wphs0326 Posted 2004-04-11 00:00
银牌会员 Posts 509 Credits 1,708 From 安徽淮南
The above are all reprinted posts. Please don't blame the original author...
Floor7 eboyzwb Posted 2004-04-24 00:00
初级用户 Posts 21 Credits 185
Awesome!
Floor8 hendry2003 Posted 2004-04-25 00:00
初级用户 Posts 20 Credits 192 From 上海市
Excuse me, senior at the 2nd floor, isn't FOR a special command for batch files? Why did you change it to FOR1 in the example below? I'm a novice, can you explain it to me? Thanks.
Floor9 jjwj Posted 2004-05-14 00:00
初级用户 Posts 18 Credits 163
Great! I'm quite inexperienced. I want to learn from the senior.
Floor10 laochang409 Posted 2004-06-18 00:00
中级用户 Posts 44 Credits 297
Thank you very much! Go back and digest it slowly.
[ Contact the Union admin team - 中国DOS联盟 - Standard version ]
Sponsored by ifanr Inc | © 2001–2023