How to loop through an array of strings in Bash?

To loop through an array of strings in Bash, use a for loop with the array’s elements expanded using "${array[@]}". Here’s how:

Basic Loop Through Array Elements

# Declare an array
fruits=("apple" "banana" "cherry" "date")

# Loop through each element
for fruit in "${fruits[@]}"; do
  echo "Fruit: $fruit"
done

Output:

Fruit: apple
Fruit: banana
Fruit: cherry
Fruit: date

Loop with Indexes

Iterate using the array’s indices (e.g., for modifying elements):

for i in "${!fruits[@]}"; do
  echo "Index $i: ${fruits[$i]}"
done

Output:

Index 0: apple
Index 1: banana
Index 2: cherry
Index 3: date

Key Notes

  1. Syntax:
  • "${array[@]}": Expands to all elements (preserves spaces in elements).
  • "${!array[@]}": Expands to all indices (useful for indexed loops).
  • Always quote "${array[@]}" to handle spaces/special characters correctly.
  1. Avoid "${array[*]}"
    "${array[*]}" merges elements into a single string (usually not desired).

Example with Spaces in Elements

# Array with elements containing spaces
items=("first item" "second item" "third item")

for item in "${items[@]}"; do
  echo "Item: $item"
done

Output:

Item: first item
Item: second item
Item: third item

Modifying Array Elements

Update elements while looping (using index-based loop):

for i in "${!fruits[@]}"; do
  fruits[$i]="${fruits[$i]} pie"  # Append " pie" to each element
done

echo "${fruits[@]}"  # Output: apple pie banana pie cherry pie date pie

Common Pitfalls

  • Forgetting Quotes:
    for fruit in ${fruits[@]} → Fails if elements contain spaces.
  • Using * Instead of @:
    for fruit in "${fruits[*]}" → Treats the entire array as a single string.

Summary

  • Basic Loop:
    for element in "${array[@]}"; do ... done
  • Index-Based Loop:
    for i in "${!array[@]}"; do ... done
  • Always Quote "${array[@]}" to handle spaces and special characters.

Leave a Reply

Your email address will not be published. Required fields are marked *