NeuroAgent

How to Loop Through Arrays in Bash Scripting

Learn the correct syntax for looping through arrays in Bash scripting. Complete guide with examples for iterating through 15 strings, avoiding common mistakes, and mastering array iteration techniques.

Question

How to loop through an array of strings in Bash scripting?

I need to write a script that iterates through 15 strings stored in an array. Is this possible in Bash? Here’s what I’ve tried:

bash
for databaseName in listOfNames
then
  # Do something
done

What’s the correct syntax for iterating through an array of strings in Bash, and how can I properly implement this loop structure?

NeuroAgent

In Bash scripting, you can loop through an array of strings using the for loop syntax with the correct array declaration and iteration pattern. Your current syntax is missing proper array declaration and the then keyword is incorrect - Bash loops use do instead of then to start the loop body.

Contents


Creating Arrays in Bash

Before you can loop through an array, you need to properly declare it. Bash supports several ways to create arrays:

Indexed Arrays

bash
# Method 1: Using parentheses
listOfNames=("database1" "database2" "database3")

# Method 2: Assigning individual elements
listOfNames[0]="database1"
listOfNames[1]="database2"
listOfNames[2]="database3"

# Method 3: Using declare -a
declare -a listOfNames
listOfNames=("db1" "db2" "db3")

Associative Arrays

bash
# Associative arrays (key-value pairs) require bash 4+
declare -A db_config
db_config["host"]="localhost"
db_config["port"]="5432"

Basic Array Iteration Syntax

Here’s the correct syntax for looping through your array:

bash
# Proper array declaration
listOfNames=("database1" "database2" "database3")

# Correct loop syntax
for databaseName in "${listOfNames[@]}"; do
  # Do something with databaseName
  echo "Processing database: $databaseName"
done

Key elements to note:

  • Use do instead of then to start the loop body
  • Use "${array[@]}" to iterate through all elements
  • The loop variable (databaseName) gets each array value in sequence

Complete Example with 15 Strings

Here’s a complete working example with 15 database names:

bash
#!/bin/bash

# Create array with 15 database names
listOfNames=(
  "production_db"
  "staging_db"
  "development_db"
  "testing_db"
  "backup_db"
  "analytics_db"
  "reporting_db"
  "cache_db"
  "session_db"
  "user_db"
  "product_db"
  "order_db"
  "inventory_db"
  "log_db"
  "archive_db"
)

# Loop through the array
echo "Starting database processing..."
echo "============================="

for databaseName in "${listOfNames[@]}"; do
  echo "Processing database: $databaseName"
  
  # Example operation: Check if database exists
  # if psql -U postgres -c "\l" | grep -q "$databaseName"; then
  #   echo "  ✓ Database exists"
  # else
  #   echo "  ✗ Database not found"
  # fi
  
  # Add your processing logic here
  # Connect to database, run queries, etc.
  
  echo "---------------------------"
done

echo "All databases processed successfully!"

Different Array Types

Indexed Arrays (Most Common)

bash
# Standard indexed array
servers=("web1" "web2" "web3" "db1" "db2")

# Loop through indexed array
for server in "${servers[@]}"; do
  echo "Server: $server"
done

Associative Arrays

bash
# Bash 4+ required for associative arrays
declare -A user_roles
user_roles["alice"]="admin"
user_roles["bob"]="developer"
user_roles["charlie"]="user"

# Loop through associative array
for user in "${!user_roles[@]}"; do
  role="${user_roles[$user]}"
  echo "User: $user, Role: $role"
done

Array Slicing

bash
# Get first 5 elements
first_five=("${listOfNames[@]:0:5}")

# Get elements from index 3 to end
from_third=("${listOfNames[@]:3}")

Advanced Looping Techniques

While Loop with Array Indexing

bash
listOfNames=("db1" "db2" "db3")
index=0

while [ $index -lt ${#listOfNames[@]} ]; do
  databaseName="${listOfNames[$index]}"
  echo "Processing index $index: $databaseName"
  ((index++))
done

C-Style For Loop

bash
for ((i=0; i<${#listOfNames[@]}; i++)); do
  databaseName="${listOfNames[$i]}"
  echo "Index $i: $databaseName"
done

Processing Array Elements with Operations

bash
# Convert array to uppercase
upper_array=("${listOfNames[@]^}")

# Add prefix to each element
prefixed_array=("prod_${listOfNames[@]}")

# Filter array elements
filtered_array=($(for name in "${listOfNames[@]}"; do
  [[ $name =~ .*prod.* ]] && echo "$name"
done))

Common Mistakes and Solutions

Mistake 1: Missing Quotes Around Array

bash
# WRONG - This won't handle spaces properly
for name in $listOfNames; do

# CORRECT - Use quotes to preserve spaces
for name in "${listOfNames[@]}"; do

Mistake 2: Using then Instead of do

bash
# WRONG
for name in "${array[@]}"; then

# CORRECT
for name in "${array[@]}"; do

Mistake 3: Not Accessing Array Elements Correctly

bash
# WRONG - This references the array as a single string
for name in "$listOfNames"; do

# CORRECT - Use [@] to iterate through elements
for name in "${listOfNames[@]}"; do

Mistake 4: Forgetting Array Declaration

bash
# WRONG - listOfNames is just a string variable
listOfNames="db1 db2 db3"

# CORRECT - Declare as array
listOfNames=("db1" "db2" "db3")

Best Practices

  • Always use "${array[@]}" syntax for iteration
  • Quote array expansion to handle spaces and special characters
  • Use descriptive variable names
  • Add error handling for empty arrays
  • Document your array contents in comments

Sources

  1. Bash Guide for Beginners - Arrays
  2. Advanced Bash-Scripting Guide - Chapter 27 Arrays
  3. Stack Overflow - Bash iterate over array
  4. GeeksforGeeks - Bash Arrays
  5. DigitalOcean - How To Use Arrays in Bash Scripts

Conclusion

Looping through arrays in Bash scripting is straightforward once you understand the correct syntax. The key takeaways are:

  • Always declare your arrays properly using parentheses: listOfNames=("db1" "db2" "db3")
  • Use for variable in "${array[@]}"; do for iteration, not then
  • Quote your array expansion to handle spaces and special characters
  • Bash supports both indexed arrays (0-based) and associative arrays (Bash 4+)
  • You can process 15 strings or any number of elements using the same loop structure

For your specific case with 15 database names, the complete solution would be to declare your array with all 15 strings and use the proper for loop syntax shown in the examples above. This approach will work reliably in any modern Bash environment and handle all the edge cases like spaces in database names.