Arrays

When you need to store multiple values - file lists, server names, configuration options - arrays are your tool.

Creating Arrays

hljs bash
#!/bin/bash

# Method 1: Direct assignment
fruits=("apple" "banana" "cherry")

# Method 2: One at a time
colors[0]="red"
colors[1]="green"
colors[2]="blue"

# Method 3: From command output
files=($(ls *.txt))

Accessing Elements

hljs bash
#!/bin/bash

fruits=("apple" "banana" "cherry")

echo "${fruits[0]}"   # apple (first element)
echo "${fruits[1]}"   # banana
echo "${fruits[2]}"   # cherry
echo "${fruits[-1]}"  # cherry (last element)

Use Braces

$fruits[0] doesn't work as expected. Always use ${fruits[0]}.

All Elements

hljs bash
#!/bin/bash

fruits=("apple" "banana" "cherry")

echo "${fruits[@]}"  # apple banana cherry (as separate words)
echo "${fruits[*]}"  # apple banana cherry (as single string)

Array Length

hljs bash
#!/bin/bash

fruits=("apple" "banana" "cherry")

echo "${#fruits[@]}"    # 3 (number of elements)
echo "${#fruits[0]}"    # 5 (length of first element "apple")

Looping Through Arrays

hljs bash
#!/bin/bash

servers=("web1" "web2" "db1" "db2")

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

Quote the Array

Always use "${array[@]}" with quotes. Without quotes, elements with spaces break into multiple items.

Adding Elements

hljs bash
#!/bin/bash

fruits=("apple" "banana")

# Append
fruits+=("cherry")
fruits+=("date" "elderberry")

echo "${fruits[@]}"  # apple banana cherry date elderberry

Removing Elements

hljs bash
#!/bin/bash

fruits=("apple" "banana" "cherry" "date")

# Remove by index
unset 'fruits[1]'  # Removes "banana"

echo "${fruits[@]}"  # apple cherry date

# Note: This leaves a gap! Index 1 is now empty
echo "${fruits[1]}"  # (empty)
echo "${fruits[2]}"  # cherry

To reindex after removal:

hljs bash
fruits=("${fruits[@]}")  # Repack array

Slicing Arrays

hljs bash
#!/bin/bash

letters=("a" "b" "c" "d" "e" "f")

echo "${letters[@]:2}"    # c d e f (from index 2)
echo "${letters[@]:2:3}"  # c d e (3 elements starting at index 2)

Array Indices

hljs bash
#!/bin/bash

fruits=("apple" "banana" "cherry")

# Get all indices
echo "${!fruits[@]}"  # 0 1 2

# Loop with indices
for i in "${!fruits[@]}"; do
    echo "$i: ${fruits[$i]}"
done

Associative Arrays (Dictionaries)

hljs bash
#!/bin/bash

# Must declare as associative
declare -A user

user[name]="John"
user[email]="john@example.com"
user[role]="admin"

echo "${user[name]}"    # John
echo "${user[email]}"   # john@example.com

# All keys
echo "${!user[@]}"      # name email role

# All values
echo "${user[@]}"       # John john@example.com admin

Practical Examples

Config Array

hljs bash
#!/bin/bash

declare -A config

config[host]="localhost"
config[port]="8080"
config[debug]="true"

# Use config
curl "http://${config[host]}:${config[port]}/api"

Process File List

hljs bash
#!/bin/bash

# Collect files
backup_files=()

for f in /etc/*.conf; do
    [[ -f "$f" ]] && backup_files+=("$f")
done

echo "Found ${#backup_files[@]} config files"

# Process them
for file in "${backup_files[@]}"; do
    cp "$file" /backup/
done

Multiple Servers

hljs bash
#!/bin/bash

declare -A servers=(
    [web]="192.168.1.10"
    [db]="192.168.1.20"
    [cache]="192.168.1.30"
)

for name in "${!servers[@]}"; do
    ip="${servers[$name]}"
    echo "Checking $name ($ip)..."
done
Knowledge Check

How do you get the number of elements in an array?

Quick Reference

SyntaxPurpose
arr=("a" "b" "c")Create array
${arr[0]}Access element
${arr[@]}All elements
${#arr[@]}Array length
${!arr[@]}All indices
arr+=("d")Append
unset 'arr[1]'Remove element
declare -A arrAssociative array

Key Takeaways

  • Create arrays with arr=("a" "b" "c")
  • Access elements with ${arr[index]}
  • Always quote "${arr[@]}" when expanding
  • ${#arr[@]} gives array length
  • Use declare -A for key-value pairs
  • Arrays are great for file lists, configs, server names

Next: string manipulation techniques.