Use For Loop With Array in Bash
Loops as the name suggests are used to repeat the same task with specified conditions.
Previously, in the guide to how to append to an array in bash, I used a simple for loop to print every element of an array and this guide is supposed to be an expansion of that part.
And in this guide, I will show you two ways to do so:
- Iterating for loop for every item
- Using an index in an array
Let's start with the first one.
Use for loop with array for every element
In this method, you can use a variable that will be used to print every element of the array.
You can use any name for the variable to store the value of the element for the ongoing iteration. Here, I went with the item
as a variable.
And this is the syntax that you have to follow to get the job done:
#Loop part
for item in "${Array_name[@]}"
do
echo $item
done
For example, here's my array named arrVar
which contains text elements as follows:
arrVar=( "One" "Two" "Three" )
And if I put the values respectively, the script would look like this:
#!/bin/bash
arrVar=( "One" "Two" "Three" )
#Loop part
for item in "${arrVar[@]}"
do
echo $item
done
Finally, save the file and make it executable using the chmod command and you can expect the following results after execution:
Use index to print values of array in bash
This method uses a typical for loop where you declare the initial value, a condition, and if the condition is true then an action (increment or decrement).
Here's a simple syntax to get the work done:
for (( i=0; i<${#array_name[@]}; i++ ));
do
echo ${array_name[$i]}
done
In the above syntax, I used i
as a variable and will print each element till the value of every element is greater than the i
variable.
For example, here's the array named arrVar
that I want to work with:
arrVar=( "1" "2" "3" "4" )
So if I add my variable name in the loop, the final version would look like this:
#!/bin/bash
arrVar=( "1" "2" "3" "4" )
#Loop part
for (( i=0; i<${#arrVar[@]}; i++ ));
do
echo ${arrVar[$i]}
done
You can expect the following output if you used my example:
And there you have it!
Level up your bash game for FREE!
If you are a beginner and want to learn bash for free, we have prepared a complete guide that will take care of all the basics:
I hope the arrays are not the horrifying part anymore.