G
GuideDevOps
Lesson 7 of 15

Arrays

Part of the Shell Scripting (Bash) tutorial series.

Indexed Arrays

Creating Arrays

# Method 1: List assignment
arr=("value1" "value2" "value3")
 
# Method 2: Individual elements
arr[0]="value1"
arr[1]="value2"
arr[2]="value3"
 
# Method 3: Empty array
arr=()
arr+=("new value")

Accessing Elements

arr=("apple" "banana" "cherry")
 
# Single element
echo "${arr[0]}"          # apple
echo "${arr[1]}"          # banana
echo "${arr[2]}"          # cherry
echo "${arr[-1]}"         # cherry (last element)

Array Length and Indices

arr=("one" "two" "three" "four" "five")
 
# Number of elements
echo "${#arr[@]}"          # 5
 
# Indices
echo "${!arr[@]}"          # 0 1 2 3 4
 
# Length of specific element
echo "${#arr[0]}"          # 3 (length of "one")

Iterating Arrays

arr=("apple" "banana" "cherry")
 
# Loop over elements
for item in "${arr[@]}"; do
    echo "$item"
done
 
# Loop over indices
for i in "${!arr[@]}"; do
    echo "Index $i: ${arr[$i]}"
done

Array Operations

Adding Elements

arr=("one" "two")
 
# Append
arr+=("three")             # arr now has 3 elements
arr+=("four" "five")      # Add multiple
 
# Insert (requires manipulation)
arr=("${arr[@]:0:1}" "new" "${arr[@]:1}")

Removing Elements

arr=("one" "two" "three" "four")
 
# Remove specific index
unset arr[1]               # Removes "two"
 
# Remove all elements
unset arr[@]
 
# Get array without element
arr=("${arr[@]/#two/}")    # Remove "two"

Slicing Arrays

arr=("a" "b" "c" "d" "e")
 
# Get subset
echo "${arr[@]:1:3}"       # b c d (start at 1, length 3)
echo "${arr[@]:2}"         # c d e (from index 2 to end)
echo "${arr[@]:0:2}"       # a b (first 2 elements)

Associative Arrays (Hashes)

Declaration and Assignment

# Must declare as associative
declare -A person
 
person[name]="Alice"
person[age]="30"
person[city]="NYC"
 
# Access
echo "${person[name]}"     # Alice
echo "${person[age]}"      # 30

Iterate Associative Array

declare -A config
config[host]="localhost"
config[port]="3306"
config[user]="admin"
 
# All values
for value in "${config[@]}"; do
    echo "$value"
done
 
# All keys
for key in "${!config[@]}"; do
    echo "$key: ${config[$key]}"
done

String to Array Conversion

# Split string into array
string="apple,banana,cherry"
IFS=',' read -ra arr <<< "$string"
 
# Now arr has three elements
for item in "${arr[@]}"; do
    echo "$item"
done
 
# Join array into string
arr=("one" "two" "three")
string=$(IFS=,; echo "${arr[*]}")
echo "$string"            # one,two,three

Practical Examples

Processing File List

files=($(find /var/log -name "*.log" -type f))
 
echo "Found ${#files[@]} log files"
 
for logfile in "${files[@]}"; do
    size=$(stat -f%z "$logfile" 2>/dev/null || stat -c%s "$logfile")
    echo "$logfile: $size bytes"
done

Configuration Array

declare -A db_config=(
    [server]="localhost"
    [port]="5432"
    [user]="postgres"
    [password]="secret"
)
 
echo "Connecting to ${db_config[server]}:${db_config[port]}"