Iterating over Arrays

Iterating over arrays needs to be done in order to write less and maintainable code scripts. We need to iterate the elements of the array one by one or in a particular pattern in such a way that we don’t have to manually echo the elements. We can achieve this in the following ways.

Method 1:

@echo off 
set list="foo" "bar" "baz"
(for %%a in (%list%) do ( 
   echo %%a 
))

In this approach we are using range-based for loops, i.e. we will iterate over the array until it is empty hence the word, for .. in … So after the for loop syntax we can say the keyword, do to execute the commands until the loop is iterable. The contents of the array at every index are stored in the variable “a”, which can be anything as sensible. 

Now using this approach we can iterate over arrays using the iterator and then we can echo them. We can modify the contents as well by accessing the original array and index of the element. 

Batch Script – Iterating Over an Array

A batch script is a set of instructions or a script for SOS and Windows Operating System. We can write them in the CMD line by line or we can create a file with a  “.bat” or “.cmd” extension. The file can contain valid instructions for executing by the interpreter. The meaning of batch is the non-interactive execution of the instructions. We can add logic and conditional blocks of programming in such scripts. 

Similar Reads

Iterating over Arrays

Iterating over arrays needs to be done in order to write less and maintainable code scripts. We need to iterate the elements of the array one by one or in a particular pattern in such a way that we don’t have to manually echo the elements. We can achieve this in the following ways....

Method 2:

@echo off set x[0]=cricket set x[1]=football set x[2]=hockey set x[3]=golf set x[4]=volleyball for /L %%a in (0,1,4) do call echo %%x[%%a]%%...