『楼 主』:
关于DOS下.bat批量处理的详细解释
使用 LLM 解释/回答一下
关于DOS下.bat批量处理的详细解释
.bat是dos下的批处理文件
.cmd是nt内核命令行环境的另一种批处理文件
从更广义的角度来看,unix的shell脚本以及其它操作系统甚至应用程序中由外壳进行解释执行的文本,都具有与批处理文件十分相似的作用,而且同样是由专用解释器以行为单位解释执行,这种文本形式更通用的称谓是脚本语言。所以从某个程度分析,batch, unix shell, awk, basic, perl 等脚本语言都是一样的,只不过应用的范围和解释的平台各有不同而已。甚至有些应用程序仍然沿用批处理这一称呼,而其内容和扩展名与dos的批处理却又完全不同。
===================================
首先批处理文件是一个文本文件,这个文件的每一行都是一条DOS命令(大部分时候就好象我们在DOS提示符下执行的命令行一样),你可以使用DOS下的Edit或者Windows的记事本(notepad)等任何文本文件编辑工具创建和修改批处理文件。
==== 注 ===================
批处理文件中完全可以使用非dos命令,甚至可以使用不具有可执行特性的普通数据性文件,这缘于windows系统这个新型解释平台的涉入,使得批处理的应用越来越"边缘化"。所以我们讨论的批处理应该限定在dos环境或者命令行环境中,否则很多观念和设定都需要做比较大的变动。
========================
其次,批处理文件是一种简单的程序,可以通过条件语句(if)和流程控制语句(goto)来控制命令运行的流程,在批处理中也可以使用循环语句(for)来循环执行一条命令。当然,批处理文件的编程能力与C语言等编程语句比起来是十分有限的,也是十分不规范的。批处理的程序语句就是一条条的DOS命令(包括内部命令和外部命令),而批处理的能力主要取决于你所使用的命令。
==== 注 ==================
批处理文件(batch file)也可以称之为批处理程序(batch program),这一点与编译型语言有所不同,就c语言来说,扩展名为c或者cpp的文件可以称之为c语言文件或者c语言源代码,但只有编译连接后的exe文件才可以称之为c语言程序。因为批处理文件本身既具有文本的可读性,又具有程序的可执行性,这些称谓的界限是比较模糊的。
===========================
第三,每个编写好的批处理文件都相当于一个DOS的外部命令,你可以把它所在的目录放到你的DOS搜索路径(path)中来使得它可以在任意位置运行。一个良好的习惯是在硬盘上建立一个bat或者batch目录(例如C:\BATCH),然后将所有你编写的批处理文件放到该目录中,这样只要在path中设置上c:\batch,你就可以在任意位置运行所有你编写的批处理程序。
==== 注 =====
纯以dos系统而言,可执行程序大约可以细分为五类,依照执行优先级由高到低排列分别是:DOSKEY宏命令(预先驻留内存),COMMAND.COM中的内部命令(根据内存的环境随时进驻内存),以com为扩展名的可执行程序(由command.com 直接载入内存),以exe位扩展名的可执行程序(由command.com 重定位后载入内存),以bat位扩展名的批处理程序(由command.com 解释分析,根据其内容按优先级顺序调用第2,3,4,5种可执行程序,分析一行,执行一行,文件本身不载入内存)
============
第四,在DOS和Win9x/Me系统下,C:盘根目录下的AUTOEXEC.BAT批处理文件是自动运行批处理文件,每次系统启动时会自动运行该文件,你可以将系统每次启动时都要运行的命令放入该文件中,例如设置搜索路径,调入鼠标驱动和磁盘缓存,设置系统环境变量等。下面是一个运行于Windows 98下的autoexec.bat的示例:
@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
==== 注 =====
AUTOEXEC.BAT为DOS系统的自动运行批处理文件,由COMMAND.COM启动时解释执行;
而在Win9x环境中,不仅增加支持了 DOSSTART.BAT, WINSTART.BAT 等许多其它自动运行的批处理文件,对AUTOEXEC.BAT 也增加了 .DOS .W40 .BAK .OLD .PWS 等许多变体以适应复杂的环境和多变的需求。
==== willsort 编注 =============
以下关于命令的分类,有很多值得推敲的地方。常用命令中的@本不是命令,而dir、copy等也很常用的命令却没有列入, 而特殊命令中所有命令对我来说都是常用命令。建议将批处理所引用的命令分为内部命令、外部命令、第三方程序三类。而内部命令和外部命令中别有一类是专用于或常用于批处理中的命令可称之为"批处理命令"。
以下摘录MS-DOS 6.22 帮助文档中关于"批处理命令"的文字,当然,其中有些概念和定义已经有些落后了。
批处理命令
批处理文件或批处理程序是一个包含若干MS-DOS命令的正文文件,扩展名为.BAT。当在命令提示符下敲入批处理程序的名称时,MS-DOS成组执行此批处理程序中的命令。
任何在命令提示符下可使用的命令都可用在批处理程序中。此外,下面MS-DOS命令是专门在批处理程序中使用的。
==========
常用命令
echo、@、call、pause、rem(小技巧:用::代替rem)是批处理文件最常用的几个命令,我们就从他们开始学起。
==== 注 ===========
首先, @ 不是一个命令, 而是DOS 批处理的一个特殊标记符, 仅用于屏蔽命令行回显. 下面是DOS命令行或批处理中可能会见到的一些特殊标记符:
CR(0D) 命令行结束符
Escape(1B) ANSI转义字符引导符
Space(20) 常用的参数界定符
Tab(09) ; = 不常用的参数界定符
+ COPY命令文件连接符
* ? 文件通配符
"" 字符串界定符
| 命令管道符
< > >> 文件重定向符
@ 命令行回显屏蔽符
/ 参数开关引导符
: 批处理标签引导符
% 批处理变量引导符
其次, :: 确实可以起到rem 的注释作用, 而且更简洁有效; 但有两点需要注意:
第一, 除了 :: 之外, 任何以 :开头的字符行, 在批处理中都被视作标号, 而直接忽略其后的所有内容, 只是为了与正常的标号相区别, 建议使用 goto 所无法识别的标号, 即在 :后紧跟一个非字母数字的一个特殊符号.
第二, 与rem 不同的是, ::后的字符行在执行时不会回显, 无论是否用echo on打开命令行回显状态, 因为命令解释器不认为他是一个有效的命令行, 就此点来看, rem 在某些场合下将比 :: 更为适用; 另外, rem 可以用于 config.sys 文件中.
=====================
echo 表示显示此命令后的字符
echo off 表示在此语句后所有运行的命令都不显示命令行本身
@与echo off相象,但它是加在每个命令行的最前面,表示运行时不显示这一行的命令行(只能影响当前行)。
call 调用另一个批处理文件(如果不用call而直接调用别的批处理文件,那么执行完那个批处理文件后将无法返回当前文件并执行当前文件的后续命令)。
pause 运行此句会暂停批处理的执行并在屏幕上显示Press any key to continue...的提示,等待用户按任意键后继续
rem 表示此命令后的字符为解释行(注释),不执行,只是给自己今后参考用的(相当于程序中的注释)。
==== 注 =====
此处的描述较为混乱, 不如直接引用个命令的命令行帮助更为条理
-------------------------
ECHO
当程序运行时,显示或隐藏批处理程序中的正文。也可用于允许或禁止命令的回显。
在运行批处理程序时,MS-DOS一般在屏幕上显示(回显)批处理程序中的命令。
使用ECHO命令可关闭此功能。
语法
ECHO
若要用echo命令显示一条命令,可用下述语法:
echo
参数
ON|OFF
指定是否允许命令的回显。若要显示当前的ECHO的设置,可使用不带参数的ECHO
命令。
message
指定让MS-DOS在屏幕上显示的正文。
-------------------
CALL
从一个批处理程序中调用另一个批处理程序,而不会引起第一个批处理的中止。
语法
CALL filename
参数
filename
指定要调用的批处理程序的名字及其存放处。文件名必须用.BAT作扩展名。
batch-parameters
指定批处理程序所需的命令行信息。
-------------------------------
PAUSE
暂停批处理程序的执行并显示一条消息,提示用户按任意键继续执行。只能在批处
理程序中使用该命令。
语法
PAUSE
REM
在批处理文件或CONFIG.SYS中加入注解。也可用REM命令来屏蔽命令(在CONFIG.SYS
中也可以用分号 ; 代替REM命令,但在批处理文件中则不能替代)。
语法
REM
参数
string
指定要屏蔽的命令或要包含的注解。
=======================
例1:用edit编辑a.bat文件,输入下列内容后存盘为c:\a.bat,执行该批处理文件后可实现:将根目录中所有文件写入 a.txt中,启动UCDOS,进入WPS等功能。
批处理文件的内容为: 命令注释:
@echo off 不显示后续命令行及当前命令行
dir c:\*.* >a.txt 将c盘文件列表写入a.txt
call c:\ucdos\ucdos.bat 调用ucdos
echo 你好 显示"你好"
pause 暂停,等待按键继续
rem 准备运行wps 注释:准备运行wps
cd ucdos 进入ucdos目录
wps 运行wps
批处理文件的参数
批处理文件还可以像C语言的函数一样使用参数(相当于DOS命令的命令行参数),这需要用到一个参数表示符"%"。
%表示参数,参数是指在运行批处理文件时在文件名后加的以空格(或者Tab)分隔的字符串。变量可以从%0到%9,%0表示批处理命令本身,其它参数字符串用%1到%9顺序表示。
例2:C:根目录下有一批处理文件名为f.bat,内容为:
@echo off
format %1
如果执行C:\>f a:
那么在执行f.bat时,%1就表示a:,这样format %1就相当于format a:,于是上面的命令运行时实际执行的是format a:
例3:C:根目录下一批处理文件名为t.bat,内容为:
@echo off
type %1
type %2
那么运行C:\>t a.txt b.txt
%1 : 表示a.txt
%2 : 表示b.txt
于是上面的命令将顺序地显示a.txt和b.txt文件的内容。
==== 注 ===============
参数在批处理中也作为变量处理, 所以同样使用百分号作为引导符, 其后跟0-9中的一个数字构成参数引用符. 引用符和参数之间 (例如上文中的 %1 与 a: ) 的关系类似于变量指针与变量值的关系. 当我们要引用第十一个或更多个参数时, 就必须移动DOS 的参数起始指针. shift 命令正充当了这个移动指针的角色, 它将参数的起始指针移动到下一个参数, 类似C 语言中的指针操作. 图示如下:
初始状态, cmd 为命令名, 可以用 %0 引用
cmd arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8 arg9 arg10
^ ^ ^ ^ ^ ^ ^ ^ ^ ^
| | | | | | | | | |
%0 %1 %2 %3 %4 %5 %6 %7 %8 %9
经过1次shift后, cmd 将无法被引用
cmd arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8 arg9 arg10
^ ^ ^ ^ ^ ^ ^ ^ ^ ^
| | | | | | | | | |
%0 %1 %2 %3 %4 %5 %6 %7 %8 %9
经过2次shift后, arg1也被废弃, %9指向为空, 没有引用意义
cmd arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8 arg9 arg10
^ ^ ^ ^ ^ ^ ^ ^ ^
| | | | | | | | |
%0 %1 %2 %3 %4 %5 %6 %7 %8
遗憾的是, win9x 和DOS下均不支持 shift 的逆操作. 只有在 nt 内核命令行环境下, shift 才支持 /n 参数, 可以以第一参数为基准返复移动起始指针.
=================
特殊命令
if goto choice for是批处理文件中比较高级的命令,如果这几个你用得很熟练,你就是批处理文件的专家啦。
一、if 是条件语句,用来判断是否符合规定的条件,从而决定执行不同的命令。 有三种格式:
1、if "参数" == "字符串" 待执行的命令
参数如果等于(not表示不等,下同)指定的字符串,则条件成立,运行命令,否则运行下一句。
例:if "%1"=="a" format a:
====
if 的命令行帮助中关于此点的描述为:
IF string1==string2 command
在此有以下几点需要注意:
1. 包含字符串的双引号不是语法所必须的, 而只是习惯上使用的一种"防空"字符
2. string1 未必是参数, 它也可以是环境变量, 循环变量以及其他字符串常量或变量
3. command 不是语法所必须的, string2 后跟一个空格就可以构成一个有效的命令行
=============================
2、if exist 文件名 待执行的命令
如果有指定的文件,则条件成立,运行命令,否则运行下一句。
如: if exist c:\config.sys type c:\config.sys
表示如果存在c:\config.sys文件,则显示它的内容。
****** 注 ********
也可以使用以下的用法:
if exist command
device 是指DOS系统中已加载的设备, 在win98下通常有:
AUX, PRN, CON, NUL
COM1, COM2, COM3, COM4
LPT1, LPT2, LPT3, LPT4
XMSXXXX0, EMMXXXX0
A: B: C: ...,
CLOCK$, CONFIG$, DblBuff$, IFS$HLP$
具体的内容会因硬软件环境的不同而略有差异, 使用这些设备名称时, 需要保证以下三点:
1. 该设备确实存在(由软件虚拟的设备除外)
2. 该设备驱动程序已加载(aux, prn等标准设备由系统缺省定义)
3. 该设备已准备好(主要是指a: b: ..., com1..., lpt1...等)
可通过命令 mem/d | find "device" /i 来检阅你的系统中所加载的设备
另外, 在DOS系统中, 设备也被认为是一种特殊的文件, 而文件也可以称作字符设备; 因为设备(device)与文件都是使用句柄(handle)来管理的, 句柄就是名字, 类似于文件名, 只不过句柄不是应用于磁盘管理, 而是应用于内存管理而已, 所谓设备加载也即指在内存中为其分配可引用的句柄.
==================================
3、if errorlevel <数字> 待执行的命令
很多DOS程序在运行结束后会返回一个数字值用来表示程序运行的结果(或者状态),通过if errorlevel命令可以判断程序的返回值,根据不同的返回值来决定执行不同的命令(返回值必须按照从大到小的顺序排列)。如果返回值等于指定的数字,则条件成立,运行命令,否则运行下一句。
如if errorlevel 2 goto x2
==== 注 ===========
返回值从大到小的顺序排列不是必须的, 而只是执行命令为 goto 时的习惯用法, 当使用 set 作为执行命令时, 通常会从小到大顺序排列, 比如需将返回码置入环境变量, 就需使用以下的顺序形式:
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
...
当然, 也可以使用以下循环来替代, 原理是一致的:
for %%e in (1 2 3 4 5 6 7 8...) do if errorlevel %%e set el=%%e
更高效简洁的用法, 可以参考我写的另一篇关于获取 errorlevel 的文章
出现此种现象的原因是, if errorlevel 比较返回码的判断条件并非等于, 而是大于等于. 由于 goto 的跳转特性, 由小到大排序会导致在较小的返回码处就跳出; 而由于 set命令的 "重复" 赋值特性, 由大到小排序会导致较小的返回码 "覆盖" 较大的返回码.
另外, 虽然 if errorlevel=<数字> command 也是有效的命令行, 但也只是 command.com 解释命令行时将 = 作为命令行切分符而忽略掉罢了
===========================
二、goto 批处理文件运行到这里将跳到goto所指定的标号(标号即label,标号用:后跟标准字符串来定义)处,goto语句一般与if配合使用,根据不同的条件来执行不同的命令组。
如:
goto end
:end
echo this is the end
标号用":字符串"来定义,标号所在行不被执行。
==== willsort 编注
label 常被译为 "标签" , 但是这并不具有广泛的约定性.
goto 与 : 联用可实现执行中途的跳转, 再结合 if 可实现执行过程的条件分支, 多个 if 即可实现命令的分组, 类似 C 中 switch case 结构或者 Basic 中的 select case 结构, 大规模且结构化的命令分组即可实现高级语言中的函数功能. 以下是批处理和C/Basic在语法结构上的对照:
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()
==================================
三、choice 使用此命令可以让用户输入一个字符(用于选择),从而根据用户的选择返回不同的errorlevel,然后于if errorlevel配合,根据用户的选择运行不同的命令。
注意:choice命令为DOS或者Windows系统提供的外部命令,不同版本的choice命令语法会稍有不同,请用choice /?查看用法。
choice的命令语法(该语法为Windows 2003中choice命令的语法,其它版本的choice的命令语法与此大同小异):
CHOICE
描述:
该工具允许用户从选择列表选择一个项目并返回所选项目的索引。
参数列表:
/C choices 指定要创建的选项列表。默认列表是 "YN"。
/N 在提示符中隐藏选项列表。提示前面的消息得到显示,
选项依旧处于启用状态。
/CS 允许选择分大小写的选项。在默认情况下,这个工具
是不分大小写的。
/T timeout 做出默认选择之前,暂停的秒数。可接受的值是从 0
到 9999。如果指定了 0,就不会有暂停,默认选项
会得到选择。
/D choice 在 nnnn 秒之后指定默认选项。字符必须在用 /C 选
项指定的一组选择中; 同时,必须用 /T 指定 nnnn。
/M text 指定提示之前要显示的消息。如果没有指定,工具只
显示提示。
/? 显示帮助消息。
注意:
ERRORLEVEL 环境变量被设置为从选择集选择的键索引。列出的第一个选
择返回 1,第二个选择返回 2,等等。如果用户按的键不是有效的选择,
该工具会发出警告响声。如果该工具检测到错误状态,它会返回 255 的
ERRORLEVEL 值。如果用户按 Ctrl+Break 或 Ctrl+C 键,该工具会返回 0
的 ERRORLEVEL 值。在一个批程序中使用 ERRORLEVEL 参数时,将参数降
序排列。
示例:
CHOICE /?
CHOICE /C YNC /M "确认请按 Y,否请按 N,或者取消请按 C。"
CHOICE /T 10 /C ync /CS /D y
CHOICE /C ab /M "选项 1 请选择 a,选项 2 请选择 b。"
CHOICE /C ab /N /M "选项 1 请选择 a,选项 2 请选择 b。"
==== willsort 编注 ===============================
我列出win98下choice的用法帮助, 已资区分
Waits for the user to choose one of a set of choices.
等待用户选择一组待选字符中的一个
CHOICE choices] c,nn]
/Cchoices Specifies allowable keys. Default is YN
指定允许的按键(待选字符), 默认为YN
/N Do not display choices and ? at end of prompt string.
不显示提示字符串中的问号和待选字符
/S Treat choice keys as case sensitive.
处理待选字符时大小写敏感
/Tc,nn Default choice to c after nn seconds
在 nn 秒后默认选择 c
text Prompt string to display
要显示的提示字符串
ERRORLEVEL is set to offset of key user presses in choices.
ERRORLEVEL 被设置为用户键入的字符在待选字符中的偏移值
如果我运行命令:CHOICE /C YNC /M "确认请按 Y,否请按 N,或者取消请按 C。"
屏幕上会显示:
确认请按 Y,否请按 N,或者取消请按 C。 ?
例:test.bat的内容如下(注意,用if errorlevel判断返回值时,要按返回值从高到低排列):
@echo off
choice /C dme /M "defrag,mem,end"
if errorlevel 3 goto end
if errorlevel 2 goto mem
if errorlevel 1 goto defrag
:defrag
c:\dos\defrag
goto end
:mem
mem
goto end
:end
echo good bye
此批处理运行后,将显示"defrag,mem,end?" ,用户可选择d m e ,然后if语句根据用户的选择作出判断,d表示执行标号为defrag的程序段,m表示执行标号为mem的程序段,e表示执行标号为end的程序段,每个程序段最后都以goto end将程序跳到end标号处,然后程序将显示good bye,批处理运行结束。
四、for 循环命令,只要条件符合,它将多次执行同一命令。
语法:
对一组文件中的每一个文件执行某个特定命令。
FOR %%variable IN (set) DO command
%%variable 指定一个单一字母可替换的参数。
(set) 指定一个或一组文件。可以使用通配符。
command 指定对每个文件执行的命令。
command-parameters
为特定命令指定参数或命令行开关。
例如一个批处理文件中有一行:
for %%c in (*.bat *.txt) do type %%c
则该命令行会显示当前目录下所有以bat和txt为扩展名的文件的内容。
==== willsort 编注 =====================================================
需要指出的是, 当()中的字符串并非单个或多个文件名时, 它将单纯被当作字符串替换, 这个特性再加上()中可以嵌入多个字符串的特性, 很明显 for 可以被看作一种遍历型循环.
当然, 在 nt/2000/xp/2003 系列的命令行环境中, for 被赋予了更多的特性, 使之可以分析命令输出或者文件中的字符串, 也有很多开关被用于扩展了文件替换功能.
========================================================================
批处理示例
1. IF-EXIST
1) 首先用记事本在C:\建立一个test1.bat批处理文件,文件内容如下:
@echo off
IF EXIST \AUTOEXEC.BAT TYPE \AUTOEXEC.BAT
IF NOT EXIST \AUTOEXEC.BAT ECHO \AUTOEXEC.BAT does not exist
然后运行它:
C:\>TEST1.BAT
如果C:\存在AUTOEXEC.BAT文件,那么它的内容就会被显示出来,如果不存在,批处理就会提示你该文件不存在。
2) 接着再建立一个test2.bat文件,内容如下:
@ECHO OFF
IF EXIST \%1 TYPE \%1
IF NOT EXIST \%1 ECHO \%1 does not exist
执行:
C:\>TEST2 AUTOEXEC.BAT
该命令运行结果同上。
说明:
(1) IF EXIST 是用来测试文件是否存在的,格式为
IF EXIST 命令
(2) test2.bat文件中的%1是参数,DOS允许传递9个批参数信息给批处理文件,分别为%1~%9(%0表示test2命令本身) ,这有点象编程中的实参和形参的关系,%1是形参,AUTOEXEC.BAT是实参。
==== willsort 编注 =====================================================
DOS没有 "允许传递9个批参数信息" 的限制, 参数的个数只会受到命令行长度和所调用命令处理能力的限制. 但是, 我们在批处理程序中, 在同一时刻只能同时引用10个参数, 因为 DOS只给出了 %0~%9这十个参数引用符.
========================================================================
3) 更进一步的,建立一个名为TEST3.BAT的文件,内容如下:
@echo off
IF "%1" == "A" ECHO XIAO
IF "%2" == "B" ECHO TIAN
IF "%3" == "C" ECHO XIN
如果运行:
C:\>TEST3 A B C
屏幕上会显示:
XIAO
TIAN
XIN
如果运行:
C:\>TEST3 A B
屏幕上会显示
XIAO
TIAN
在这个命令执行过程中,DOS会将一个空字符串指定给参数%3。
2、IF-ERRORLEVEL
建立TEST4.BAT,内容如下:
@ECHO OFF
XCOPY C:\AUTOEXEC.BAT D:\
IF ERRORLEVEL 1 ECHO 文件拷贝失败
IF ERRORLEVEL 0 ECHO 成功拷贝文件
然后执行文件:
C:\>TEST4
如果文件拷贝成功,屏幕就会显示"成功拷贝文件",否则就会显示"文件拷贝失败"。
IF ERRORLEVEL 是用来测试它的上一个DOS命令的返回值的,注意只是上一个命令的返回值,而且返回值必须依照从大到小次序顺序判断。
因此下面的批处理文件是错误的:
@ECHO OFF
XCOPY C:\AUTOEXEC.BAT D:\
IF ERRORLEVEL 0 ECHO 成功拷贝文件
IF ERRORLEVEL 1 ECHO 未找到拷贝文件
IF ERRORLEVEL 2 ECHO 用户通过ctrl-c中止拷贝操作
IF ERRORLEVEL 3 ECHO 预置错误阻止文件拷贝操作
IF ERRORLEVEL 4 ECHO 拷贝过程中写盘错误
无论拷贝是否成功,后面的:
未找到拷贝文件
用户通过ctrl-c中止拷贝操作
预置错误阻止文件拷贝操作
拷贝过程中写盘错误
都将显示出来。
以下就是几个常用命令的返回值及其代表的意义:
backup
0 备份成功
1 未找到备份文件
2 文件共享冲突阻止备份完成
3 用户用ctrl-c中止备份
4 由于致命的错误使备份操作中止
diskcomp
0 盘比较相同
1 盘比较不同
2 用户通过ctrl-c中止比较操作
3 由于致命的错误使比较操作中止
4 预置错误中止比较
diskcopy
0 盘拷贝操作成功
1 非致命盘读/写错
2 用户通过ctrl-c结束拷贝操作
3 因致命的处理错误使盘拷贝中止
4 预置错误阻止拷贝操作
format
0 格式化成功
3 用户:)
### Detailed Explanation of Batch Processing under DOS
A `.bat` is a batch processing file under DOS. A `.cmd` is another type of batch processing file in the NT kernel command line environment. From a broader perspective, Unix shell scripts and texts in other operating systems or even applications that are interpreted and executed by the shell have very similar functions to batch processing files. Moreover, they are all interpreted and executed line by line by a dedicated interpreter. A more general term for this text form is scripting language. So, from a certain perspective, scripting languages such as batch, Unix shell, awk, basic, perl, etc., are the same, except that they are applied in different ranges and interpreted on different platforms. Even some applications still use the term "batch processing," but their content and extensions are completely different from those of DOS batch processing.
===================================
First, a batch processing file is a text file. Each line of this file is a DOS command (most of the time, it is just like the command line we execute under the DOS prompt). You can use text file editing tools such as Edit under DOS or Notepad under Windows to create and modify batch processing files.
==== Note ===================
A batch processing file can completely use non-DOS commands, and even ordinary data files that do not have executable characteristics. This is due to the involvement of the new interpretation platform of the Windows system, which makes the application of batch processing more "marginalized". Therefore, the batch processing we discuss should be limited to the DOS environment or command line environment, otherwise, many concepts and settings need to be changed significantly.
========================
Second, a batch processing file is a simple program. You can use conditional statements (if) and process control statements (goto) to control the flow of command execution. In batch processing, you can also use loop statements (for) to execute a command in a loop. Of course, the programming ability of batch processing files is very limited and not standardized compared with programming statements such as the C language. The program statements of batch processing are just one by one DOS commands (including internal commands and external commands), and the ability of batch processing mainly depends on the commands you use.
==== Note ==================
A batch processing file (batch file) can also be called a batch processing program (batch program). This is different from compiled languages. For example, for the C language, files with extensions c or cpp can be called C language files or C language source codes, but only the exe file after compilation and linking can be called a C language program. Because the batch processing file itself has both readability of text and executability of a program, the boundaries of these designations are relatively blurred.
===========================
Third, each well-written batch processing file is equivalent to an external command of DOS. You can put the directory where it is located into your DOS search path (path) so that it can run in any position. A good habit is to create a bat or batch directory (for example, C:\BATCH) on the hard disk, and then put all the batch processing files you write into this directory. In this way, as long as you set c:\batch in the path, you can run all the batch processing programs you write in any position.
==== Note =====
Purely in terms of the DOS system, executable programs can be roughly divided into five categories, arranged in descending order of execution priority: DOSKEY macro commands (pre-resident in memory), internal commands in COMMAND.COM (reside in memory according to the memory environment at any time), executable programs with the com extension (directly loaded into memory by command.com), executable programs with the exe extension (relocated and loaded into memory by command.com), and batch processing programs with the bat extension (interpreted and analyzed by command.com, and call the 2nd, 3rd, 4th, and 5th types of executable programs in order of priority according to its content, analyze one line and execute one line, and the file itself is not loaded into memory)
============
Fourth, under the DOS and Win9x/Me systems, the AUTOEXEC.BAT batch processing file in the root directory of the C drive is an automatically running batch processing file. It will automatically run this file every time the system starts. You can put the commands that need to be run every time the system starts into this file, such as setting the search path, loading the mouse driver and disk cache, setting the system environment variables, etc. The following 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
==== Note =====
AUTOEXEC.BAT is an automatically running batch processing file of the DOS system, which is interpreted and executed when COMMAND.COM starts;
In the Win9x environment, not only many other automatically running batch processing files such as DOSSTART.BAT, WINSTART.BAT, etc., are added to support, but also many variants such as .DOS .W40 .BAK .OLD .PWS, etc., are added to AUTOEXEC.BAT to adapt to complex environments and changing needs.
==== willsort Annotation =============
There are many places worthy of discussion in the following classification of commands. The @ in common commands is not a command, and commands such as dir, copy, etc., which are also very common, are not listed, while all commands in special commands are common commands to me. It is recommended to divide the commands referred to by batch processing into three categories: internal commands, external commands, and third-party programs. And among internal commands and external commands, there is another category of commands that are specially used or often used in batch processing, which can be called "batch processing commands".
The following is an excerpt from the MS-DOS 6.22 help document about "batch processing commands". Of course, some of these concepts and definitions are a bit outdated.
Batch Processing Commands
A batch processing file or batch processing program is a text file containing several MS-DOS commands with the extension .BAT. When the name of the batch processing program is typed at the command prompt, MS-DOS executes the commands in this batch processing program in groups.
Any command that can be used at the command prompt can be used in a batch processing program. In addition, the following MS-DOS commands are specially used in batch processing programs.
==========
Common Commands
echo, @, call, pause, rem (tips: use :: instead of rem) are the most commonly used commands in batch processing files. Let's start learning from them.
==== Note ===========
First, @ is not a command, but a special mark in DOS batch processing, only used to shield command line echoing. The following are some special marks that may be seen in DOS command lines or batch processing:
CR(0D) Command line end character
Escape(1B) ANSI escape character guide character
Space(20) Common parameter delimiter
Tab(09) ; = Less commonly used parameter delimiter
+ COPY command file concatenation character
* ? File wildcards
"" String delimiter
| Command pipeline character
< > >> File redirection character
@ Command line echoing shielding character
/ Parameter switch guide character
: Batch processing label guide character
% Batch processing variable guide character
Second, :: can indeed play the role of rem comment, and it is more concise and effective; but there are two points to note:
First, except for ::, any character line starting with : is regarded as a label in batch processing, and all content after it is directly ignored. Just to distinguish it from normal labels, it is recommended to use a special symbol that cannot be recognized by goto, that is, a special symbol other than letters and numbers is followed after :.
Second, different from rem, the character line after :: will not be echoed during execution, regardless of whether the command line echoing state is turned on by echo on, because the command interpreter does not consider it a valid command line. In this regard, rem will be more applicable than :: in some occasions; in addition, rem can be used in the config.sys file.
=====================
echo means to display the characters after this command.
echo off means that all commands running after this statement do not display the command line itself.
@ is similar to echo off, but it is added in front of each command line, indicating that this line of command is not displayed during running (only affects the current line).
call calls another batch processing file (if you directly call another batch processing file without call, then after executing that batch processing file, you will not be able to return to the current file and execute the subsequent commands of the current file).
pause running this sentence will pause the execution of the batch processing and display the prompt Press any key to continue... on the screen, waiting for the user to press any key to continue.
rem means that the characters after this command are explanatory lines (comments), which are not executed, just for reference for the future (equivalent to comments in the program).
==== Note =====
The description here is relatively chaotic,不如 directly refer to the command line help of each command for a more organized description.
-------------------------
ECHO
When the program runs, it displays or hides the text in the batch processing program. It can also be used to allow or prohibit the echoing of commands.
When running a batch processing program, MS-DOS generally displays (echoes) the commands in the batch processing program on the screen.
Use the ECHO command to turn off this function.
Syntax
ECHO
If you want to use the echo command to display a command, you can use the following syntax:
echo
Parameters
ON|OFF
Specify whether to allow the echoing of commands. If you want to display the current ECHO setting, you can use the ECHO command without parameters.
message
Specify the text that MS-DOS displays on the screen.
-------------------
CALL
Call another batch processing program from a batch processing program without causing the first batch processing to stop.
Syntax
CALL filename
Parameters
filename
Specify the name and storage location of the batch processing program to be called. The file name must use .BAT as the extension.
batch-parameters
Specify the command line information required by the batch processing program.
-------------------------------
PAUSE
Pause the execution of the batch processing program and display a message, prompting the user to press any key to continue execution. This command can only be used in batch processing programs.
Syntax
PAUSE
REM
Add comments in the batch processing file or CONFIG.SYS. The REM command can also be used to shield commands (semicolons ; can be used instead of REM commands in CONFIG.SYS, but not in batch processing files).
Syntax
REM
Parameters
string
Specify the command to be shielded or the comment to be included.
=======================
Example 1: Use edit to edit the a.bat file, enter the following content and save it as c:\a.bat. After executing this batch processing 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 processing file: command comments:
@echo off Do not display subsequent command lines and current command line.
dir c:\*.* >a.txt Write the file list of the C drive into a.txt.
call c:\ucdos\ucdos.bat Call ucdos.
echo Hello Display "Hello".
pause Pause and wait for the key to continue.
rem Prepare to run wps Comment: Prepare to run wps.
cd ucdos Enter the ucdos directory.
wps Run wps.
Parameters of Batch Processing Files
Batch processing files can also use parameters like functions in the C language (equivalent to command line parameters of DOS commands). This requires using a parameter identifier "%".
% means parameters. Parameters refer to the strings separated by spaces (or Tab) after the file name when running the batch processing file. Variables can range from %0 to %9. %0 represents the batch processing command itself, and other parameter strings are represented in sequence by %1 to %9.
Example 2: There is a batch processing file named f.bat in the root directory of C, and the content is:
@echo off
format %1
If you execute C:\>f a:
Then when executing f.bat, %1 means a:, so format %1 is equivalent to format a:, so the above command actually executes format a: when running.
Example 3: There is a batch processing file named t.bat in the root directory of C, and the content is:
@echo off
type %1
type %2
Then run C:\>t a.txt b.txt.
%1: Represents a.txt.
%2: Represents b.txt.
Then the above command will sequentially display the contents of the a.txt and b.txt files.
==== Note ===============
Parameters are also treated as variables in batch processing, so the percent sign is also used as a guide character. A number from 0-9 is followed by it to form a parameter reference character. The relationship between the reference character and the parameter (such as %1 and a: in the above text) is similar to the relationship between a variable pointer and a variable value. When we want to reference the eleventh or more parameters, we must move the parameter start pointer of DOS. The shift command acts as this pointer moving role, which moves the parameter start pointer to the next parameter, similar to the pointer operation in the C language. The diagram is as follows:
Initial state, cmd is the command name, which can be referenced by %0.
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 cannot 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 to empty, which has no reference meaning.
cmd arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8 arg9 arg10
^ ^ ^ ^ ^ ^ ^ ^ ^
| | | | | | | | |
%0 %1 %2 %3 %4 %5 %6 %7 %8
Unfortunately, win9x and DOS do not support the reverse operation of shift. Only in the NT kernel command line environment does shift support the /n parameter, which can repeatedly move the start pointer with the first parameter as the benchmark.
=================
Special Commands
if, goto, choice, for are relatively advanced commands in batch processing files. If you use these well, you are an expert in batch processing files.
1. if is a conditional statement used to judge whether the specified conditions are 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 (not means not equal, the same below) the specified string, then the condition is established, and the command is run; otherwise, the next sentence is run.
Example: if "%1"=="a" format a:
====
The description in the command line help of if about this point is:
IF string1==string2 command.
The following points need to be noted here:
1. The double quotes containing the string are not necessary for grammar, but are just a kind of "anti-air" character used by habit.
2. string1 is not necessarily a parameter, it can also be an environment variable, a loop variable, and other string constants or variables.
3. command is not necessary for grammar, and a space can be followed after string2 to form a valid command line.
=============================
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 c:\config.sys type c:\config.sys.
It means that if the c:\config.sys file exists, then display its content.
****** Note ********
The following usage can also be used:
if exist command.
device refers to the devices loaded in the DOS system. In win98, there are 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 be slightly different due to the different hardware and software environments. When using these device names, the following three points need to be ensured:
1. The device does exist (except for the devices virtualized by software).
2. The device driver has been loaded (standard devices such as aux, prn are defined by the system by default).
3. The device is ready (mainly referring to a: b: ..., com1..., lpt1... etc.).
You can use the command mem/d | find "device" /i to check the devices loaded in your system.
In addition, in the DOS system, the device is also considered a special file, and the file can also be called a character device; because the device (device) and the file are both managed by handles (handle), the handle is the name, similar to the file name, except that the handle is not applied to disk management, but to memory management. The so-called device loading also means that a referenceable handle is allocated for it in memory.
==================================
3. if errorlevel <number> command to be executed.
Many DOS programs return a numerical value to indicate the running result (or status) of the program after running. Through the if errorlevel command, you can judge the return value of the program, and decide to execute different commands according to different return values (the return values must be arranged in descending order). 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.
For example, if errorlevel 2 goto x2.
==== Note ===========
The arrangement of return values in descending order is not necessary, but it is just a habitual usage when the command is goto. When using set as the execution command, it is usually arranged in ascending order. For example, if you need to put the return code into an environment variable, you need to use the following order form:
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, the following loop can also be used to replace, the principle is the same:
for %%e in (1 2 3 4 5 6 7 8...) do if errorlevel %%e set el=%%e.
A more efficient and concise usage can refer to another article I wrote about obtaining errorlevel.
The reason for this phenomenon is that the judgment condition of if errorlevel <number> command is not equal, but greater than or equal. Due to the jump characteristic of goto, sorting from small to large will cause jumping out at a smaller return code; and due to the "repeated" assignment characteristic of the set command, sorting from large to small will cause a smaller return code to "override" a larger return code.
In addition, although if errorlevel=<number> command is also a valid command line, it is just that command.com ignores the = as a command line delimiter when interpreting the command line.
===========================
2. goto The batch processing will jump to the label (label is label, the label is defined by : followed by a standard string) specified by goto when running to here. The goto statement is generally used in conjunction with if to execute different command groups according to different conditions.
For example:
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.
==== willsort Annotation
label is often translated as "label", but this is not universally agreed.
goto and : used together can realize the jump in the middle of execution. Combined with if, it can realize the conditional branch of the execution process. Multiple ifs can realize 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 realize the function of functions in high-level languages. The following is the comparison of syntax structures between batch processing and C/Basic:
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()
==================================
3. choice Using this command can let the user enter a character (used for selection), so as to return different errorlevels according to the user's selection, and then cooperate with if errorlevel to run different commands according to the user's selection.
Note: The choice command is an external command provided by the DOS or Windows system. The syntax of the choice command in different versions will be slightly different. Please use choice /? to view the usage.
The command syntax of choice (this syntax is the syntax of the choice command in Windows 2003. The command syntax of choice in other versions is similar to this):
CHOICE
Description:
This tool allows the user to select an item from the selection list and return the index of the selected item.
Parameter list:
/C choices Specifies the option list to be created. The default list is "YN".
/N Hides the option list in the prompt. The message before the prompt is displayed, and the options are still enabled.
/CS Allows selecting case-sensitive options. By default, this tool is case-insensitive.
/T timeout The number of seconds to pause before making the default selection. The acceptable value is from 0 to 9999. If 0 is specified, there will be no pause, and the default option will be selected.
/D choice Specifies the default option after nnnn seconds. The character must be in the set of choices specified by /C option; at the same time, /T must be used to specify nnnn.
/M text Specifies the message to be displayed before the prompt. If not specified, the tool only displays the prompt.
/? Displays the help message.
Note:
The ERRORLEVEL environment variable is set to the key index selected from the selection set. The first selected choice returns 1, the second choice returns 2, and so on. If the key pressed by the user is not a valid choice, the tool will make a warning beep. If the tool detects an error state, it will return an ERRORLEVEL value of 255. If the user presses Ctrl+Break or Ctrl+C key, the tool will return an ERRORLEVEL value of 0. When using the ERRORLEVEL parameter in a batch program, arrange the parameters in descending order.
Example:
CHOICE /?
CHOICE /C YNC /M "Please press Y to confirm, N to refuse, or C to cancel."
CHOICE /T 10 /C ync /CS /D y
CHOICE /C ab /M "Please select a for option 1, and b for option 2."
CHOICE /C ab /N /M "Please select a for option 1, and b for option 2."
==== willsort Annotation ===============================
I list the usage help of choice under win98 for reference for distinction.
Waits for the user to choose one of a set of choices.
CHOICE choices] c,nn]
/Cchoices Specifies allowable keys. Default is YN.
/N Do not display choices and ? at end of prompt string.
/S Treat choice keys as case sensitive.
/Tc,nn Default choice to c after nn seconds.
text Prompt string to display.
ERRORLEVEL is set to offset of key user presses in choices.
If I run the command: CHOICE /C YNC /M "Please press Y to confirm, N to refuse, or C to cancel."
The screen will display:
Please press Y to confirm, N to refuse, or C to cancel. ?
Example: The content of test.bat is as follows (note that when using if errorlevel to judge the return value, it should be arranged in descending order of return value):
@echo off
choice /C dme /M "defrag,mem,end"
if errorlevel 3 goto end
if errorlevel 2 goto mem
if errorlevel 1 goto defrag
:defrag
c:\dos\defrag
goto end
:mem
mem
goto end
:end
echo good bye
After this batch processing runs, it will display "defrag,mem,end?", the user can choose d, m, e, and then the if statement makes a judgment according to the user's choice. 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 jumps to the end label with goto end, and then the program will display good bye, and the batch processing ends.
4. for loop command, it will execute the same command multiple times as long as the condition is met.
Syntax:
Execute a specific command for each file in a group of files.
FOR %%variable IN (set) DO command
%%variable specifies a single letter replaceable parameter.
(set) specifies one or a group of files. Wildcards can be used.
command specifies the command to be 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 processing file:
for %%c in (*.bat *.txt) do type %%c.
Then this command line will display the contents of all files with extensions bat and txt in the current directory.
==== willsort Annotation =====================================================
It needs to be pointed out that when the string in () is not a single or multiple file names, it will simply be regarded as a string replacement. This feature, combined with the feature that multiple strings can be embedded in (), it is obvious that for can be regarded as a traversal loop.
Of course, in the command line environment of the nt/2000/xp/2003 series, for is given more features, so that it can analyze the output of commands or strings in files, and there are also many switches used to expand the file replacement function.
========================================================================
Batch Processing Examples
1. IF-EXIST
1) First, use Notepad to create a test1.bat batch processing file in C:\. The file content is as follows:
@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 the AUTOEXEC.BAT file exists in C:\, then its content will be displayed. If it does not exist, the batch processing will prompt you that the file does not exist.
2) Then create a test2.bat file with the following content:
@ECHO OFF
IF EXIST \%1 TYPE \%1
IF NOT EXIST \%1 ECHO \%1 does not exist.
Execute:
C:\>TEST2 AUTOEXEC.BAT.
The running result of this command is the same as above.
Description:
(1) IF EXIST is used to test whether the file exists. The format is:
IF EXIST command.
(2) The %1 in the test2.bat file is a parameter. DOS allows passing 9 batch parameter information to the batch processing file, which are %1~%9 respectively (%0 represents the test2 command itself). This is a bit like the relationship between actual parameters and formal parameters in programming. %1 is a formal parameter, and AUTOEXEC.BAT is an actual parameter.
==== willsort Annotation =====================================================
DOS does not have the limit of "allowing to pass 9 batch parameter information". The number of parameters will only be limited by the command line length and the processing ability of the called command. However, in the batch processing program, at the same time, you can only refer to 10 parameters, because DOS only gives these ten parameter reference characters %0~%9.
========================================================================
3) Further, create a file named TEST3.BAT with the following content:
@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 this command execution, DOS will assign an empty string to parameter %3.
2. IF-ERRORLEVEL.
Create TEST4.BAT with the following content:
@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 copy is successful, the screen will display "File copied successfully", otherwise it will display "File copy failed".
IF ERRORLEVEL is used to test the return value of its 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 processing file is wrong:
@ECHO OFF
XCOPY C:\AUTOEXEC.BAT D:\
IF ERRORLEVEL 0 ECHO File copied successfully.
IF ERRORLEVEL 1 ECHO File not found.
IF ERRORLEVEL 2 ECHO User aborted copy operation by ctrl-c.
IF ERRORLEVEL 3 ECHO Pre-set error prevented file copy operation.
IF ERRORLEVEL 4 ECHO Write error during copy operation.
No matter whether the copy is successful or not, the following:
File not found.
User aborted copy operation by ctrl-c.
Pre-set error prevented file copy operation.
Write error during copy operation.
All will be displayed.
The following are the return values of several common commands and their meanings:
backup
0 Backup successful.
1 Backup file not found.
2 File sharing conflict prevented backup from completing.
3 User aborted backup by ctrl-c.
4 Backup operation aborted due to a fatal error.
diskcomp
0 Disks compared the same.
1 Disks compared differently.
2 User aborted comparison operation by ctrl-c.
3 Comparison operation aborted due to a fatal error.
4 Pre-set error aborted comparison.
diskcopy
0 Disk copy operation successful.
1 Non-fatal disk read/write error.
2 User ended copy operation by ctrl-c.
3 Disk copy aborted due to a fatal processing error.
4 Pre-set error prevented copy operation.
format
0 Formatting successful.
3 User:)
|