前面章节介绍了 for 语句的基础用法,以及 for /D、for /R 扩展用法。
本节将介绍 for /L 扩展用法。for /L 用使用给定信息创建序列,语法如下:
FOR /L %variable IN (start,step,end) DO command [command-parameters]上面语法中其他指令已经在前面介绍过,for /L 表示以增量形式从 start 以每次增加 step,直到到 end 的一个数字序列。如果 start 小于 end,就会执行该命令。如果迭代变量超过 end,则命令解释程序退出此循环。还可以使用负的 step 以递减数值的方式逐步执行此范围内的值。其他参数说明:
start:指定创建序列的开始位置
step:for 语句创建序列时单步距离。
end:指定创建序列结束位置
实例:创建 1~5 的序列。
@echo off
for /L %%i in (1,1,5) do echo %%i
pause输出结果:
C:\Users\Administrator\Desktop\bat> test.bat
1
2
3
4
5
请按任意键继续. . .实例:创建 5~1 的序列。
@echo off
for /L %%i in (5,-1,1) do echo %%i
pause输出结果:
C:\Users\Administrator\Desktop\bat> test.bat
5
4
3
2
1
请按任意键继续. . .实例:start,step 和 end 三者的数值关系。
@echo off
for /l %%i in (2,2,13) do echo %%i
pause >nul输出结果:
C:\Users\Administrator\Desktop\bat> test.bat
2
4
6
8
10
12根据实例输出的结果,可以得出如下结论:
start > end,即 2 > 13
当 step 为正时,start+step 决定 %%i 的最小取值范围,end 决定 %%i 的最大取值范围。
当 step 为负时,start+step 决定 %%i 的最大取值范围,end 决定 %%i 的最小取值范围。
实例:使用 for 创建大量的文件夹。
@echo off
cd test
for /l %%i in (1,1,100) do (
md %%i
)
echo finished.
pause >nul输出结果:
C:\Users\Administrator\Desktop\bat> test.bat
finished.查看效果图:
