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:
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?
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
- Basic Array Iteration Syntax
- Complete Example with 15 Strings
- Different Array Types
- Advanced Looping Techniques
- Common Mistakes and Solutions
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
# 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
# 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:
# 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
doinstead ofthento 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:
#!/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)
# 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 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
# 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
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
for ((i=0; i<${#listOfNames[@]}; i++)); do
databaseName="${listOfNames[$i]}"
echo "Index $i: $databaseName"
done
Processing Array Elements with Operations
# 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
# 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
# WRONG
for name in "${array[@]}"; then
# CORRECT
for name in "${array[@]}"; do
Mistake 3: Not Accessing Array Elements Correctly
# 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
# 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
- Bash Guide for Beginners - Arrays
- Advanced Bash-Scripting Guide - Chapter 27 Arrays
- Stack Overflow - Bash iterate over array
- GeeksforGeeks - Bash Arrays
- 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[@]}"; dofor iteration, notthen - 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.