在Windows批处理(* .bat)文件中嵌套

时间:2013-11-15 12:10:35

标签: android windows batch-file

我需要实现脚本,在循环中以2位数格式执行命令和内联迭代变量。我无法理解如何正确处理批处理文件中的变量。我做错了什么?

for /l %%h in (0,1,23) do (
SET padded_h1=0%%h
SET padded_h=%padded_h1:~-2%

for /l %%m in (0,1,59) do (
    SET padded_min1=0%m%
    SET padded_min=%padded_min1:~-2%

    C:\android-sdk-windows\platform-tools\adb -e shell date -s 20131202.%padded_h%%padded_min%00 
    ping 127.0.0.1 -n 2 > nul
)

2 个答案:

答案 0 :(得分:3)

批处理文件中包含变量的基本规则是:除非明确要求延迟替换,否则每个行或每个块(如果有的话)都会被解析,变量会被值替换为

这意味着内部带有varibles的for块(除了命令的%%变量)在到达时将所有变量替换为值,并且在每个循环中没有变量,只有其值。

除非启用延迟扩展且变量被引用为!var!而不是%var%

因此,当读取块时,将变量替换为其值,因此,您的代码将由cmd执行,因为它已被写入

for /l %%h in (0,1,23) do (
    SET padded_h1=0%%h
    SET padded_h=

    for /l %%m in (0,1,59) do (
        SET padded_min1=0%m%
        SET padded_min=

        C:\android-sdk-windows\platform-tools\adb -e shell date -s 20131202.00 
        ping 127.0.0.1 -n 2 > nul
    )
)

由于变量没有初始值,当读取块(从开始到结束括号),并且用它们的值替换变量时,你得到它。

因此,您的代码应该看起来像

rem Enable delayed expansion
setlocal enableextensions enabledelayedexpansion

for /l %%h in (0,1,23) do (
    rem %%h is a for variable, no problems with it
    SET padded_h1=0%%h

    rem padded_h1 has changed its value inside de for, so 
    rem we need to get the changed value not the initial value
    rem the variable had when the block was readed
    SET padded_h=!padded_h1:~-2!

    rem and the same with the inner loop    
    for /l %%m in (0,1,59) do (
        SET padded_min1=0%%m
        SET padded_min=!padded_min1:~-2!

        C:\android-sdk-windows\platform-tools\adb -e shell date -s 20131202.!padded_h!!padded_min!00 
        ping 127.0.0.1 -n 2 > nul
    )

)

答案 1 :(得分:1)

如果没有DelayedExpansion,则不能在循环内部使用for循环中设置的变量。

将其更改为:

setlocal enabledelayedexpansion
for /l %%h in (0,1,23) do (
    SET padded_h1=0%%h
    SET padded_h=!padded_h1:~-2!

    for /l %%m in (0,1,59) do (
        SET padded_min1=0%m%
        SET padded_min=!padded_min1:~-2!

        C:\android-sdk-windows\platform-tools\adb -e shell date -s 20131202.!padded_h!!padded_min!00 
        ping 127.0.0.1 -n 2 > nul
    )
)