Skip to content Skip to sidebar Skip to footer

Nested For In Windows Batch (*.bat) File

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.

Solution 1:

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.

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

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.

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

)

Solution 2:

You can't use variables set within a for loop inside of the loop without DelayedExpansion.

Change it to this:

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

Post a Comment for "Nested For In Windows Batch (*.bat) File"