Bash for Loop with Array

Introduction

In this tutorial, we will cover different methods to iterate over arrays using for loops. Arrays are a powerful data structure in Bash, and by leveraging the flexibility of for loops, we can process each element of an array efficiently. Whether you need to perform computations, concatenate strings, or work with nested arrays, this tutorial will provide you with the necessary tools to iterate over arrays effectively in Bash.

Iterating using the array elements

Bash provides a simple for-loop syntax to iterate over an array of items.

#!/bin/bash for i in "${array[@]}";do ## Process $idone

Using this syntax, bash iterates the variable i through the elements of the array one at a time. Within the for loop, we can reference $i to process the i’th element of the array.

Let’s take some examples to understand this:

Array of integers

Let us see how we can iterate over an array to compute the sum of all the numbers.

#!/bin/bash ## Declare an array of integersdeclare -a numbers=(1 2 3 4 5) sum=0 ## Iterating using for loopfor num in "${numbers[@]}"do echo "The number is $num" sum=$((sum+$num))done echo "The sum is $sum"

  • We declare an array of integers, numbers.

  • for num in "${numbers[@]}" iterates the variable num through the elements of numbers until no more elements are left.

  • Within the for loop, we add the individual elements to the sum variable.

output of a Bash script that calculates the sum of an array of numbers.

It displays each number in the array and calculates their sum, which is 15 in this case.

Array of strings

We can also iterate over an array of strings using this syntax.

Let’s consider an example to concatenate the strings in an array and print the resulting string.

#!/bin/bash ## Declare an array of stringsdeclare -a stringArr=("Learn" "here" "for" "with" "array") result="" for str in "${stringArr[@]}"do result="$result$str "done echo "The resulting string is: $result"

  • We declare an array of strings, stringArr.

  • for str in "${stringArr[@]}" iterates the variable str through the elements of stringArr until no more elements are left.

  • Within the for loop, we append the individual stringArr elements at the end of the result string.

displaying the resulting string: 'Learn here for with array' generated from the array ['Learn', 'here', 'for', 'with' 'array']

The script takes the individual elements of the stringArr array and concatenates them into a single string with spaces between each word.

Iterating using an index variable

If you are coming from the C/C++ world, you might recognize this syntax.

#!/bin/bash for ((i=0, i<${len}; i++));do ## Process "${arr[$i]}"done

Let’s take an example to print array variables at each index.

#!/bin/bash ## Declare an array of integersdeclare -a numbers=(10 2 7 8 -1) ## Get the length of the arraylen=${#numbers[@]} for ((i=0; i<$len; i++));do echo "Index: $i, number: ${numbers[$i]}"done

  • We declare an array of integers, numbers and store its size in variable len.

  • We use double parentheses for-loop syntax using the iteration index i which iterates from 0 till (len-1). Within the for loop, we can use index referencing syntax ${numbers[$i]} to process the individual elements.

Bash script output: Index 0, number 10; Index 1, number 2; Index 2, number 7; Index 3, number 8; Index 4, number -1.

Looping through nested arrays

Bash does not support multi-dimensional arrays like other programming languages. That means it can store values only on a single level. However, you can iterate through two arrays at a time by using nested for loops.

Example:

#!/bin/bash ## Initialize 2 arrays of integersdeclare -a numbers1=(3 4 1 -1 -2)declare -a numbers2=(2 7 8 9 10) ## Get the length of the arrayslen1=${#numbers1[@]}len2=${#numbers2[@]} for ((i=0; i<$len1; i++)); do for ((j=0; j<$len2; j++)); do echo "Element ($((i+1)), $((j+1))): (${numbers1[$i]}, ${numbers2[$j]})" donedone

  • We declare two arrays, numbers1, and numbers2 and store their sizes in variable len1, len2.

  • We use nested for loops to iterate over the elements of the arrays. Effectively, we can access all the combinations (len1 * len2) of the array elements.

Output of Bash script displaying elements and positions of two arrays of integers

We see 25 different pairs of array elements.

Last updated