Search code examples
batch-filecommand-lineadb

Using an iterating variable in command-line script to create file names


I'm trying to automate an adb test procedure using a batch file. After each run a file, .CloudData.txt is made. I want to preface that file name with a trial number, T1.CloudData.txt, etc. I made this test code:

echo off
set /p loops="Enter a number of iterations: "
for /l %%i in (1,1,%loops%) do (
    set file=//scard//mytest//T%%i.CloudData.txt
    echo %file%
)

So that eventually I can have something along the lines of:

echo off
set /p loops="Enter a number of iterations: "
for /l %%i in (1,1,%loops%) do (
    rem Execute adb commands for test
    set file=//scard//mytest//T%%i.CloudData.txt
    adb shell mv /sdcard/mytest/.CloudData.txt file
)

But the test returns, assuming loops = 3, /sdcard/mytest/T3.CloudData.txt 3 times. To be painfully specific, the number stored in loops is being added where %%i should be. From what I've read in the following post: bash script variable inside variable, I think I should be using an array, but that's impractical if one day I have to run the test for more than iterations than the array permits. How should I proceed?


Solution

  • You need delayed expansion:

    echo off
    setlocal enabledelayedexpansion
    set /p loops="Enter a number of iterations: "
    for /l %%i in (1,1,%loops%) do (
        rem Execute adb commands for test
        set file=//scard//mytest//T%%i.CloudData.txt
        adb shell mv /sdcard/mytest/.CloudData.txt !file!
    )
    

    The reason for %%i seems to be 3 at all three times (it isn't) is the variable %file%, which was left from a previous run of your script