例如,删除“C:\Documents and Settings\Administrator\桌面\T1\txt\批处理实验\unit1”里的a.txt文件,使用if的代码如下:
@echo off
if exist "C:\Documents and Settings\Administrator\桌面\T1\txt\批处理实验\unit1\a.txt" (
echo file is find!
del "C:\Documents and Settings\Administrator\桌面\T1\txt\批处理实验\unit1\a.txt"
) else (
echo file is not found!
)
pause>nul
将上述代码保存为if_del.bat,效果如下:
2.if——条件判断(分支)语句
1
2
3
4
5
6
7
|
@
echo
off
if
abc==ABC (
echo
abc euqal ABC
)
else
(
echo
abc not euqal ABC
)
pause>nul
|
1
2
3
4
5
6
7
|
@
echo
off
if
%errorlevel%==0 (
echo
success!
)
else
(
echo
failed!
)
pause>nul
|
1
2
3
4
5
6
7
8
|
@
echo
off
if
exist C:\a.txt (
echo
file
is
find
!
del C:\a.txt
)
else
(
echo
file
is not found!
)
pause>nul
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
@
echo
off
set
var1=123
set
var2=abc
set
var3=12
if
/i
%var2% equ ABC (
if
%var1% geq %var3% (
echo
%var1%^>=%var3%
)
else
(
echo
%var1%^<%var3%
)
)
else
(
echo
%var2%不等于ABC
)
pause>nul
|
3.setlocal/endlocal——启动/结束延迟环境变量扩展功能
1
2
3
4
5
6
7
8
9
10
11
12
|
@
echo
off
set
var=before
if
"%var%"
==
"before"
(
set
var=after
if
"%var%"
==
"after"
(
echo
重置var的值成功[var=%var%]
)
else
(
echo
重置var的值失败[var=%var%]
)
)
echo
var=%var%
pause>nul
|
1
2
3
4
5
6
7
8
9
10
11
12
|
@
echo
off
setlocal enableDelayedExpansion
set
var=before
if
"!var!"
==
"before"
(
set
var=after
if
"!var!"
==
"after"
(
echo
重置var的值成功[var=!var!]
)
else
(
echo
重置var的值失败[var=!var!]
)
)
pause>nul
|