嵌套在Windows批处理(* .bat)文件 [英] Nested for in windows batch (*.bat) file

查看:159
本文介绍了嵌套在Windows批处理(* .bat)文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要实现脚本,在循环有执行命令和在线迭代varible 2位格式。我不明白如何正确地在批处理文件中变量的工作。我做错了吗?

I need to implement script that in loop executes command and inline iteration varible there in 2 digit format. I can't understand how to properly work with variables in batch file. What I'm doing wrong?

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
)

推荐答案

在批处理文件变量的基本规则是:每行,或者每个块(如果有),被解析并用值替换变量 readed时,除非明确要求延迟替代。

The basic rule with variables in batch files is: each line, or each block if there is one, is parsed and variables replaced with values when readed, unless explicitly asked for delayed substitution.

这意味着里面可变因素(除了命令%%变量)块得到与值替换所有变量到达时,在每个循环没有变量,只是它的值。

That means that a for block with varibles inside (except the %% variables of the command) get all variables replaced with values when it is reached, and in each loop there are no variables, just its values.

除非延迟扩充被启用和变量作为!VAR参考!代替%VAR%

Except if delayed expansion is enabled and variables are referenced as !var! instead of %var%

所以,用替代变量的值时,该块被读取,按原样,因为它已经被写入了code是通过CMD执行

So, with the variables replaced with its valued when the block is read, as is, your code is executed by cmd as it is has been written

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
    )
)

由于变量没有初始值,当块(从开始到结束括号)被读取,和变量与他们的价值观所取代,你得到这个。

As the variables have no initial value, when for block (from start to end parenthesis) is read, and variables replaced with their values, you get this.

所以,你的code看起来应该

So, your code should look as

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
    )

)

这篇关于嵌套在Windows批处理(* .bat)文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆