Script Valley
Bash Scripting for Developers
Control Flow and LogicLesson 2.4

Bash arrays and how to iterate them correctly

indexed arrays, array declaration, array access, array length, array slicing, associative arrays, iterate with for, append to array, unset array element

Arrays in Bash

Bash indexed and associative arrays

Bash has two array types: indexed (numeric keys) and associative (string keys, requires Bash 4+). Arrays are zero-indexed.

# Declare and populate
servers=("web-01" "web-02" "db-01")

# Access by index
echo ${servers[0]}    # web-01
echo ${servers[-1]}   # db-01 (last element)

# All elements
echo ${servers[@]}    # web-01 web-02 db-01

# Array length
echo ${#servers[@]}   # 3

# Append
servers+=("cache-01")

# Slice: elements 1 and 2
echo ${servers[@]:1:2}

Iterate an Array

for server in "${servers[@]}"; do
  echo "Pinging $server..."
  ping -c 1 "$server" > /dev/null && echo "OK" || echo "FAIL"
done

Always quote "${array[@]}" — without quotes, elements with spaces split into separate words.

Associative Arrays

declare -A config
config["host"]="localhost"
config["port"]="5432"
config["db"]="myapp"

echo ${config["host"]}   # localhost

# Iterate key-value pairs
for key in "${!config[@]}"; do
  echo "$key = ${config[$key]}"
done

Associative arrays require declare -A. Use them to avoid parallel arrays — instead of separate names and values arrays that must stay in sync.

Up next

Bash select menu and user input handling

Sign in to track progress