Advanced Bash & AutomationLesson 6.1
Bash arrays and associative arrays explained
indexed arrays, array assignment, array access, array iteration, array length, associative arrays, declare -A, array slicing
Arrays Store Multiple Values in One Variable
A Bash array holds multiple values indexed by number (indexed array) or string key (associative array). They are essential for processing lists of servers, files, or config entries in scripts.
Indexed Arrays
#!/bin/bash
# Declare and populate
SERVERS=("web01" "web02" "db01" "cache01")
# Access by index (zero-based)
echo "${SERVERS[0]}" # web01
echo "${SERVERS[-1]}" # cache01 (last element)
# All elements
echo "${SERVERS[@]}"
# Array length
echo "${#SERVERS[@]}"
# Iterate
for SERVER in "${SERVERS[@]}"; do
echo "Pinging: $SERVER"
done
# Append to array
SERVERS+=("monitor01")
# Slice (elements 1 and 2)
echo "${SERVERS[@]:1:2}"Associative Arrays
# Requires Bash 4+
declare -A CONFIG
CONFIG["host"]="localhost"
CONFIG["port"]="5432"
CONFIG["db"]="myapp"
# Access by key
echo "Connecting to: ${CONFIG[host]}:${CONFIG[port]}"
# All keys
echo "Keys: ${!CONFIG[@]}"
# Iterate key-value pairs
for KEY in "${!CONFIG[@]}"; do
echo "$KEY = ${CONFIG[$KEY]}"
done