Array Basics
Arrays let you store multiple values in a single variable. They're essential for handling lists of files, arguments, or any collection of data.
Creating Arrays
#!/bin/bash
# Method 1: Parentheses
FRUITS=("apple" "banana" "cherry")
# Method 2: Individual assignment
COLORS[0]="red"
COLORS[1]="green"
COLORS[2]="blue"
# Method 3: Using declare
declare -a NUMBERS=(1 2 3 4 5)
Accessing Elements
#!/bin/bash
FRUITS=("apple" "banana" "cherry" "date")
# Single element (0-indexed)
echo "${FRUITS[0]}" # apple
echo "${FRUITS[1]}" # banana
echo "${FRUITS[-1]}" # date (last element)
# All elements
echo "${FRUITS[@]}" # apple banana cherry date
echo "${FRUITS[*]}" # apple banana cherry date
Array Length
#!/bin/bash
FRUITS=("apple" "banana" "cherry")
# Number of elements
echo "${#FRUITS[@]}" # 3
# Length of specific element
echo "${#FRUITS[0]}" # 5 (length of "apple")
Exercise: Create and Access Array
Work with array elements:
Looping Over Arrays
#!/bin/bash
FRUITS=("apple" "banana" "cherry")
# Loop over values
for fruit in "${FRUITS[@]}"; do
echo "Fruit: $fruit"
done
# Loop with indices
for i in "${!FRUITS[@]}"; do
echo "$i: ${FRUITS[$i]}"
done
Adding Elements
#!/bin/bash
FRUITS=("apple" "banana")
# Append one element
FRUITS+=("cherry")
# Append multiple
FRUITS+=("date" "elderberry")
# Insert at specific index
FRUITS[10]="fig" # Creates sparse array
echo "${FRUITS[@]}"
echo "Length: ${#FRUITS[@]}"
Removing Elements
#!/bin/bash
FRUITS=("apple" "banana" "cherry" "date")
# Remove by index
unset 'FRUITS[1]' # Removes "banana"
echo "${FRUITS[@]}" # apple cherry date
# Note: This creates a sparse array!
echo "${FRUITS[1]}" # empty
echo "${FRUITS[2]}" # cherry
# To reindex after deletion
FRUITS=("${FRUITS[@]}")
Exercise: Loop Over Array
Iterate through an array:
Array Slicing
#!/bin/bash
NUMS=(0 1 2 3 4 5 6 7 8 9)
# Slice: ${array[@]:start:count}
echo "${NUMS[@]:3:4}" # 3 4 5 6
echo "${NUMS[@]:5}" # 5 6 7 8 9 (from index 5)
echo "${NUMS[@]: -3}" # 7 8 9 (last 3)
Copying Arrays
#!/bin/bash
ORIGINAL=(1 2 3 4 5)
# Copy entire array
COPY=("${ORIGINAL[@]}")
# Modify copy (doesn't affect original)
COPY[0]=99
echo "${ORIGINAL[0]}" # 1
echo "${COPY[0]}" # 99
Array from Command Output
#!/bin/bash
# Array from command output
FILES=($(ls *.txt))
# Better: handle spaces in filenames
while IFS= read -r -d '' file; do
FILES+=("$file")
done < <(find . -name "*.txt" -print0)
Checking if Array Contains Element
#!/bin/bash
FRUITS=("apple" "banana" "cherry")
contains() {
local element="$1"
shift
for item in "$@"; do
[[ "$item" == "$element" ]] && return 0
done
return 1
}
if contains "banana" "${FRUITS[@]}"; then
echo "Found banana!"
fi
Key Takeaways
- Create arrays with
ARR=(item1 item2 item3) - Access elements with
${ARR[index]}(0-indexed) - Get all elements with
"${ARR[@]}" - Get length with
${#ARR[@]} - Append with
ARR+=(new_item) - Loop with
for item in "${ARR[@]}" - Always quote:
"${ARR[@]}"to handle spaces - Use
${!ARR[@]}to get indices

