This populates an array and prints it
You could use names1 names2 names3, rather than names[1] names[2] names[3] by writing names!i! instead of names[!i!]. It produces the array by generating variable names. There isn't an array structure in batch. But it is as neat as any array structure, and populating or printing looks exactly like how one would populate or print an array in a proper language(that actually has the array structure!)
@echo off setlocal enabledelayedexpansion enableextensions set i=-1 for %%f in (bob, tom, joseph) do ( set /a i=!i!+1 set names[!i!]=%%f ) set lastindex=!i! for /L %%f in (0,1,!lastindex!) do ( echo !names[%%f]! )
the output-
c:\blah>a bob tom joseph c:\blah>
Some explanation-
The setlocal enabledelayedexpansion enableextensions
with the !var! rather than %var% is necessary to prevent odd behavior, so that variables behave properly when within a FOR or an IF. It's an oddity with batch files. See set /?
where that is mentioned further.
This is what populates the array, and is pretty straight forward to anybody that knows about arrays. You could also do names[0]=bob
names[1]=tom
names[2]=joseph
though one of the beauties of an array is the ability to populate an array with a loop, which is what i've done here.
for %%f in (bob, tom, joseph) do ( set /a i=!i!+1 set names[!i!]=%%f ) set lastindex=!i!
This displays the array. %%f if you echo it you'd see will go from 0 to the last index of the array, in steps of 1. so will print names[0] names[1] names[2]
for /L %%f in (0,1,!lastindex!) do ( echo !names[%%f]! )