In this lesson, you will learn how to organize and iterate through sets of data using Bash arrays, allowing your scripts to handle lists of information rather than just single variables.
Storing Data in Arrays
A Bash array is a variable that can hold multiple values at once. You define an array by grouping items inside parentheses, separated by spaces:
# Define an array of server names
servers=("web01" "db01" "cache01")
Once defined, you access a specific item using its index (starting from 0). For example, echo "${servers[0]}" would print web01.
Dynamic Iteration
The real power of arrays comes when you need to process data dynamically. Because your scripts might handle a list of files or users that changes, you shouldn't hardcode the array length. Instead, you use the special syntax ${#array_name[@]} to get the count of elements and the * or @ symbol to reference every element in the array.
A common pattern for dynamic processing is the for loop:
# Iterate through all elements in the array
for server in "${servers[@]}"; do
echo "Connecting to $server..."
# Perform your logic here
done
Why Use Arrays?
Arrays prevent you from having to create messy variables like server1, server2, and server3. By storing items in a structure, your code remains clean and scalable. If you need to add a new server to your list, you simply update the array definition, and the rest of your loop logic continues to function perfectly without needing any modifications.
When working with arrays, always remember to wrap your expansion in quotes—"${servers[@]}"—to ensure that if any of your data contains spaces, the shell treats that item as a single unit rather than splitting it into two separate elements. This keeps your data integrity intact as it flows through your script.
Key Takeaway: Use arrays to group related data and the "${array[@]}" syntax to loop through them safely and dynamically.