0
0
Bash Scriptingscripting~5 mins

Iterating over arrays in Bash Scripting

Choose your learning style9 modes available
Introduction
Iterating over arrays lets you do something with each item in a list, like checking or printing them one by one.
You want to print all items in a list of names.
You need to check each file in a list to see if it exists.
You want to add a prefix to every word in a list.
You want to count how many items in a list meet a condition.
Syntax
Bash Scripting
array=(item1 item2 item3)
for element in "${array[@]}"; do
  # commands using $element
  echo "$element"
done
Use double quotes around "${array[@]}" to handle items with spaces correctly.
The variable 'element' holds each item from the array during the loop.
Examples
Prints each fruit in the array one by one.
Bash Scripting
fruits=(apple banana cherry)
for fruit in "${fruits[@]}"; do
  echo "$fruit"
done
Handles an empty array gracefully by not running the loop body.
Bash Scripting
empty_array=()
for item in "${empty_array[@]}"; do
  echo "$item"
done
Works with an array that has only one item.
Bash Scripting
single_item=(onlyone)
for element in "${single_item[@]}"; do
  echo "$element"
done
Handles array items that contain spaces correctly.
Bash Scripting
words=("hello world" "foo bar" "baz")
for word in "${words[@]}"; do
  echo "$word"
done
Sample Program
This script creates an array of colors, prints them all at once, then prints each color on its own line using a loop, and finally prints the whole array again.
Bash Scripting
#!/bin/bash

# Create an array of colors
colors=(red green blue yellow)

# Print all colors before loop
printf "Colors before loop: %s\n" "${colors[*]}"

# Iterate over the array and print each color
for color in "${colors[@]}"; do
  echo "Color: $color"
done

# Print all colors after loop
printf "Colors after loop: %s\n" "${colors[*]}"
OutputSuccess
Important Notes
Time complexity is O(n) where n is the number of items in the array because each item is visited once.
Space complexity is O(n) for storing the array items.
A common mistake is not quoting "${array[@]}" which can cause items with spaces to split incorrectly.
Use array iteration when you need to process each item individually; use other methods like joining if you want to handle the whole list as one string.
Summary
Iterate over arrays using 'for element in "${array[@]}"; do ... done'.
Always quote "${array[@]}" to handle spaces in items safely.
Loops run zero times if the array is empty, which is safe.