Iterate Through a Bash Array Using “foreach” Loop [5 Examples]

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

In Bash, handling the array data structure may often cause the necessity of iterating through the array elements. While one may have encountered a loop with the foreach keyword, it must be noted that there’s no loop in Bash called foreach, and the usual for loop is used in Bash to gain similar behaviors. So, this article will shed light on the process of iterating an array in Bash using the “for” loop through element-wise iteration which will inherently serve the purpose of using the “foreach” loop mentioning 5 useful examples.

What is “foreach” Loop in Bash?

The foreach loop typically refers to the for loop that is commonly used to iterate over the elements of an array and do any kind of specific manipulation based on a given condition. It is a control flow to iterate over a set of values (array in this case). However, Bash has no specific loop with the keyword “foreach” like some other programming languages such as javascript, PHP, etc. Rather, it contains for loop that can serve the same purpose as the “foreach” loop in terms of iteration by accessing the collection of array items without to manage loop counters or indices explicitly.

The for loop in Bash is generally capable of achieving the foreach loop-like behavior by adopting such syntax where the loop iterates for the elements to access the elements. The general syntactical format is given below:

for element in "${my_array[@]}"
do
    # Commands to be executed for each element
done

Here, The loop structure somewhat looks like the dedicated foreach loop in javascript (like for each element in the array, achieve the given task for that element). The ${my_array[@]} expression expands all the array elements and the loop iterates over each element. Moreover, the variable called element (any name can be used) is used to store the elements of array for the ongoing iteration.

Ahead in this article, you’ll see 5 useful examples of iterating arrays in Bash using the “for” loop availing similar behavior of the “foreach” loop for other languages.

Iterating Arrays with “for” Loop as “foreach” in Bash

Here’s some necessary array manipulation tasks with 5 examples such as printing the array including its elements, and length using for loop:

1. Printing the Array Elements

To print the Bash array elements using the loop, use the syntax for element in "${my_array[@]}" to access each element and then print them with the echo command which displays the elements with new lines. Here’s an example:

#!/bin/bash

# Declare an array with 5 elements
my_array=("apple" "banana" "cherry" "pie" "kiwi")

# Iterate over each element in the array using a for loop
echo "array elements:"
for element in "${my_array[@]}"
do
    # Print each element as action
    echo "$element"
done
EXPLANATION

In the script, after declaring an indexed array with 5 elements, the loop for element in "${my_array[@]}" iterates the my_array, and echo "$element" prints each element to the screen one by one with new lines where “$element” represents each array element.

bash foreach array print

2. Printing the Length of an Array

Apart from printing the array elements, the for loop is also capable of getting the length of the array by iterating over each element and storing the number of elements in a counter variable with each iteration to eventually get the length.

See the example below to print the length of a Bash array using for loop:

#!/bin/bash

# Declare an array
food=("pizza" "burger" "sandwich")
#print array
echo "${food[@]}"
#set a variable to get array length via iterating each element
length=0

# Iterate over the elements of the array using a for loop
for element in "${food[@]}"
do
    # Increment the count
    ((length++))
done

echo "length: $length"
EXPLANATION

The script above declares an array called food with 3 items and the variable length with its initial value of zero. Then the loop for element in "${food[@]}" iterates through each array element individually (stimulating foreach behavior) and increments the value of length during each iteration. This effectively works as a counter to track the total number of elements of the array (which is the length actually). Finally, the command echo "length: $length" prints on the terminal.

print length of array

3. Iterating Over the Array Indices

To print only the index of each element of the specified Bash array, use the syntax for index in "${!my_array[@]}". This expression expands the array and fetches the indices instead of the corresponding elements using the exclamation mark (!) as the prefix. Here’s an example:

#!/bin/bash
# Declare an array
my_array=("element1" "element2" "element3" "element4" "element5")

# Iterate over the indices of the array using a for loop
for index in "${!my_array[@]}"
do
    # Print the current index
    echo "Index $index"
done
EXPLANATION

In the script, the Bash array named my_array has 5 elements: “element1” “element2” “element3” “element4” “element5”. The loop for index in "${!my_array[@]}" considers each item and fetches its index (0-based) using ${!my_array[@]} and prints the indices (0 1 2 3 4) to the terminal.

print index of array

4. Making a Copy of an Entire Array

Copying a Bash array refers to making a new array that contains the same elements as the original array. One common approach is to iterate over each element of the original array and append them to the copied array using the for loop like the following example:

#!/bin/bash

# Declare an array with initial elements
original_array=("world" "multiverse" "universe")
#print original array
echo "original array: ${original_array[@]}"

# Declare an empty array to copy array
copied_array=()

# Iterate over each element in the original array
for element in "${original_array[@]}"
do
    # Append the current element to the copied_array
    copied_array+=("$element")
done

# Print the copy array
echo "copy array elements:"
for element in "${copied_array[@]}"
do
    echo "$element"
done
EXPLANATION

In the script above, an array with 3 elements and an empty array is declared. Then for element in "${original_array[@]}" loop iterates over the original array and appends each element to the empty array named copied_array one by one. Finally, after printing both arrays, the success of the copy operation with the loop-based iterative approach becomes clear.

bash foreach array copy

5. Searching Over Array Elements

You can iterate over an array in Bash to search for an element using a for loop with conditional logic employing constructs such as if-else statements providing robust ways to filter and search for data within Bash arrays. Here’s an example:

#!/bin/bash
array=("apple" "banana" "orange" "grape")
found=false

for item in "${array[@]}"; do
  if [[ $item == "apple" ]]; then
    echo "Found apple!"
    found=true
    # Uncomment the following line if you want to stop after finding the first apple
    # break
  fi
done

if ! $found; then
  echo "Apple not found."
fi
EXPLANATION

Here, the script iterates through each element in array with 4 items, and checks if it’s equal to “apple”. If it finds “apple”, it prints “Found apple!” and sets the found variable to true. After the loop, if found is still false, it prints “Apple not found.”

loop with conditional logic to iterate array

Common Pitfall: Iterating an Empty Array

An empty array in Bash is an extant array but without any elements. In iterating such arrays, the loop body is never executed since the loop condition immediately becomes false due to its emptiness. See the example below for clarity:

#!/bin/bash

# Define an empty array
my_array=()

# Loop through the array
for element in "${my_array[@]}"
do
    echo "Element: $element"
done
#print the array length
echo ${#my_array[@]}

bash foreach array pitfall

Solution: Check If the Array is Empty Before Iteration

Thus, in iterating an array in Bash, it’s a good practice to check if the array is empty first since the loop might execute in unexpected ways. Here’s how to check if an array is empty before looping over it:

#!/bin/bash
empty_array=()

if [ ${#empty_array[@]} -eq 0 ]; then
    echo "Array is empty"
else
    for i in "${empty_array[@]}"
    do
        echo "Processing item: $i"
    done
fi

# Output:
# Array is empty
EXPLANATION

In the above, the script first checks if the array called empty_array is empty by calculating its length (if zero). If true, then it prints  “Array is empty” and skips the loop. Otherwise, it proceeds with the loop as usual.

pitfall solved

Conclusion

This article shows how to iterate over Bash arrays using a for loop to represent the behavior of the foreach loop. It shows 5 different examples of printing the array items, array length including array indices, and advanced operations like copying an array in Bash iteratively. In addition, it shows the iteration of arrays using a for loop with conditional logic. Hope this article has assisted you in learning about the subtleties of the “for” loop and “foreach” loop (available in other programming languages) including array iteration for necessary data manipulation tasks.

People Also Ask

Does the “foreach” loop exist in Bash?

No. Bash doesn’t have any built-in loop with the foreach loop like some other programming languages. However, you can achieve similar functionality using a for loop to iterate over each element and accomplish data handling and manipulation according to the specified condition for each element of that array.

Can I print a Bash array without using the for loop?

Yes. Use the standard expression ${array[@]} with the echo command to print a Bash array without using the for loop. For example, to print the array fruits=('apple' 'banana' 'cherry'), use the syntax echo “${fruits[@]}.

How to print array elements in newline without using for loop?

To print array elements in newline each without using the for loop, use the array expansion expression “${your_array[@]}” with the “print” command. The full syntax is printf “%s\n” “${my_array[@]}” where the \n character prints elements in newlines each. For instance, if you want to print the array  fruits=('apple' 'banana' 'cherry') with such an approach, use the syntax printf "%s\n" "${fruits[@]}.

What is the difference between the foreach loop and the for loop in Bash?

Bash has no dedicated loop with the “foreach” keyword like other languages such as PHP or javascript. This is usually a way to describe the use of a Bash for loop to iterate over array elements. You can use the for loop in Bash to achieve a similar functionality to the foreach loop available in other languages.

Can I iterate over array values using index in Bash?

Yes, you can. One approach would be, for example, to use the code array_length=${#my_array[@]} to get the length of the array and store it in the array_length variable. Then use the loop for ((i = 0; i < array_length; i++)) to iterate over the array using its indices and access the elements.

Related Articles


<< Go Back to Array Operations in Bash | Bash Array | Bash Scripting Tutorial

Rate this post
Md Masrur Ul Alam

Assalamu Alaikum, I’m Md Masrur Ul Alam, currently working as a Linux OS Content Developer Executive at SOFTEKO. I completed my Bachelor's degree in Electronics and Communication Engineering (ECE)from Khulna University of Engineering & Technology (KUET). With an inquisitive mind, I have always had a keen eye for Science and Technolgy based research and education. I strongly hope this entity leverages the success of my effort in developing engaging yet seasoned content on Linux and contributing to the wealth of technical knowledge. Read Full Bio

Leave a Comment