Creating and Using Arrays

When to Use Arrays

  • When you need to store multiple related values
  • When you want to iterate through a collection of items
  • When order of data matters
  • When you need to group command outputs or results
  • When processing lists of files, users, or any collection of items

Array Operations

Operation What It Does When to Use It
Creating Arrays Initializes a new array with values When starting to work with a collection of data
Accessing Elements Retrieves specific items by their position When you need a particular item from your collection
Modifying Elements Changes values at specific positions When updating information in your collection
Working with All Elements Processes entire array at once When performing bulk operations on your data

Practical Examples

# Creating an array of fruits
fruits=("apple" "banana" "cherry" "date")

# Accessing a specific element (remember arrays are zero-indexed)
echo "The second fruit is: ${fruits[1]}"  # Outputs: banana

# Modifying an element
fruits[3]="dragonfruit"  # Replace "date" with "dragonfruit"
echo "Updated fruit list: ${fruits[@]}"  # Outputs: apple banana cherry dragonfruit

# Getting the array length
echo "Total number of fruits: ${#fruits[@]}"  # Outputs: 4

# Adding a new element to the array
fruits+=("elderberry")
echo "New fruit list: ${fruits[@]}"  # Outputs: apple banana cherry dragonfruit elderberry

# Iterating through all elements
for fruit in "${fruits[@]}"
do
  echo "I enjoy eating $fruit"
done

# Creating an empty array and adding elements later
vegetables=()
vegetables+=("carrot")
vegetables+=("broccoli")
echo "Vegetable list: ${vegetables[@]}"  # Outputs: carrot broccoli

# Creating an array from command output
files=($(ls *.txt))  # Creates an array of all .txt files in current directory
echo "Found ${#files[@]} text files"

Advanced Array Operations

When to Use Advanced Operations

  • When you need to manipulate array slices or ranges
  • When working with array indexes dynamically
  • When you need to remove elements from arrays
  • When sorting or processing array elements
  • When you want to create associative arrays (key-value pairs)

Advanced Array Techniques

Technique What It Does When to Use It
Array Slices Extracts a portion of an array When you need a subset of your array
Associative Arrays Creates arrays with string keys instead of numeric indexes When you need key-value relationships
Array Manipulation Sorting, filtering, and transforming arrays When processing data collections

Practical Examples

# Working with array slices
numbers=(1 2 3 4 5 6 7 8 9 10)
echo "Elements 3 through 7: ${numbers[@]:3:5}"  # Outputs: 4 5 6 7 8

# Creating an associative array (requires Bash 4+)
declare -A user_info
user_info["name"]="John"
user_info["age"]="25"
user_info["city"]="Boston"

# Accessing elements in associative array
echo "Name: ${user_info["name"]}"  # Outputs: John
echo "Age: ${user_info["age"]}"    # Outputs: 25

# Iterating through associative array keys and values
for key in "${!user_info[@]}"
do
  echo "$key: ${user_info[$key]}"
done

# Removing elements from an array
unset fruits[1]  # Removes "banana" but keeps the index
echo "After removal: ${fruits[@]}"  # Outputs: apple cherry dragonfruit elderberry

# Re-indexing an array after removal
fruits=("${fruits[@]}")  # This re-indexes the array to close the gap

# Sorting an array
sorted_fruits=($(for fruit in "${fruits[@]}"; do echo "$fruit"; done | sort))
echo "Sorted fruits: ${sorted_fruits[@]}"