Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through array in batch?

I created an array like this:

set sources[0]="\\sources\folder1\" set sources[1]="\\sources\folder2\" set sources[2]="\\sources\folder3\" set sources[3]="\\sources\folder4\" 

Now I want to iterate through this array:

for %%s in (%sources%) do echo %%s 

It doesn't work! It seems that script is not going into the loop. Why is that? How can I iterate then?

like image 638
aurel Avatar asked Aug 27 '13 09:08

aurel


People also ask

How does for loop work in batch?

For loop (default) of Batch language is used to iterate over a list of files. Example: copy some files into a directory (Note: the files to be copied into the target directory need to be in the same disk drive).

What does %% mean in batch script?

%%i is simply the loop variable. This is explained in the documentation for the for command, which you can get by typing for /? at the command prompt.

What is %% g'in batch file?

%%parameter : A replaceable parameter: in a batch file use %%G (on the command line %G) FOR /F processing of a command consists of reading the output from the command one line at a time and then breaking the line up into individual items of data or 'tokens'.


1 Answers

Another Alternative using defined and a loop that doesn't require delayed expansion:

set Arr[0]=apple set Arr[1]=banana set Arr[2]=cherry set Arr[3]=donut  set "x=0"  :SymLoop if defined Arr[%x%] (     call echo %%Arr[%x%]%%     set /a "x+=1"     GOTO :SymLoop ) 

Be sure you use "call echo" as echo won't work unless you have delayedexpansion and use ! instead of %%

like image 134
Dss Avatar answered Oct 03 '22 21:10

Dss