Bash Arrays Explained
Learn how to use Bash arrays to store and manipulate multiple values in shell scripts. Covers indexed and associative arrays, practical examples, and common operations for network automation tasks.
Arrays in Bash are powerful data structures that let you store multiple values in a single variable. Think of them as containers that hold a list of items, whether that's file names, server hostnames, or configuration settings. Understanding arrays is essential for writing efficient shell scripts that can handle multiple pieces of data systematically.
What Are Bash Arrays?
A Bash array is a variable that can hold multiple values, each identified by an index number. Unlike simple variables that store one value, arrays let you group related data together and access each piece individually.
There are two types of arrays in Bash:
- Indexed arrays - Use numeric indices (0, 1, 2, etc.)
- Associative arrays - Use string keys (like "hostname" or "port")
Creating and Declaring Arrays
You can create arrays in several ways. The most straightforward method is declaring them with parentheses:
# Create an indexed array
fruits=("apple" "banana" "orange" "grape")
# Create an empty array
servers=()
# Declare an associative array (Bash 4.0+)
declare -A config
config[hostname]="webserver01"
config[port]="8080"
config[protocol]="https"You can also build arrays element by element:
# Add elements one at a time
tools[0]="nmap"
tools[1]="netstat"
tools[2]="ping"
# Or use the += operator
network_tools+=("traceroute")
network_tools+=("dig")Accessing Array Elements
To access individual elements, use the index inside curly braces with a dollar sign:
# Access specific elements
echo ${fruits[0]} # Outputs: apple
echo ${fruits[2]} # Outputs: orange
# Access associative array elements
echo ${config[hostname]} # Outputs: webserver01
echo ${config[port]} # Outputs: 8080To get all elements at once, use the @ or * symbols:
# Display all elements
echo ${fruits[@]} # Outputs: apple banana orange grape
echo ${fruits[*]} # Similar output, different behavior in quotes
# Get the number of elements
echo ${#fruits[@]} # Outputs: 4Practical Array Operations
Here's a real-world example that demonstrates common array operations for network administration:
#!/bin/bash
# Array of servers to check
servers=("192.168.1.10" "192.168.1.20" "192.168.1.30")
echo "Checking ${#servers[@]} servers..."
# Loop through array and ping each server
for server in "${servers[@]}"; do
if ping -c 1 "$server" &> /dev/null; then
echo "✓ $server is reachable"
else
echo "✗ $server is not reachable"
fi
done
# Add a new server to the array
servers+=("192.168.1.40")
echo "Added new server. Total servers: ${#servers[@]}"Array Slicing and Manipulation
Bash provides powerful ways to work with portions of arrays:
# Create a sample array
numbers=(10 20 30 40 50 60)
# Get a slice of elements (start at index 1, take 3 elements)
echo ${numbers[@]:1:3} # Outputs: 20 30 40
# Get elements from index 2 to the end
echo ${numbers[@]:2} # Outputs: 30 40 50 60
# Remove an element (unset doesn't resize the array)
unset numbers[2]
echo ${numbers[@]} # Outputs: 10 20 40 50 60Common Use Cases
Arrays shine in automation scripts where you need to process multiple items systematically:
# Process multiple log files
log_files=("/var/log/apache2/access.log" "/var/log/nginx/access.log")
for log in "${log_files[@]}"; do
if [[ -f "$log" ]]; then
echo "Processing $log..."
tail -n 100 "$log" | grep "ERROR"
fi
doneWhat's Next
Now that you understand Bash arrays, you're ready to explore more advanced shell scripting concepts. In the next post, we'll dive into Bash functions and how they work together with arrays to create modular, reusable code that makes your scripts more organized and maintainable.