Bash Array of Arrays
William McKeehan

Bash Array of Arrays

Bash Array of Arrays

This is a script that demonstrates how to create an array of arrays in bash.

Copy
#!/usr/bin/env bash

# Declare and initialize a couple of arrays
PLANTS=(rose tulip sunflower daffodil "lily of the valley")
ANIMALS=(dog cat rabbit)

echo "${#PLANTS[@]} plants"
echo "${#ANIMALS[@]} animals"
echo

# Declare and initialize an associative array
# using | as the delimiter, we join the each array into a string and assign that to the associative key
declare -A THINGS
THINGS[plants]=$(IFS='|'; echo "${PLANTS[*]}")
THINGS[animals]=$(IFS='|'; echo "${ANIMALS[*]}")

# This will print the values of the original arrays joined as a string with a delimiter of |
echo "Plants: ${THINGS[plants]}"
echo "Animals: ${THINGS[animals]}"
echo

# Now, we undo the above by splitting the string back into an array
for collection in "${!THINGS[@]}"; do
  echo $collection
  IFS='|' read -ra things <<< "${THINGS[$collection]}"
  for thing in "${things[@]}"; do
    echo "    $thing"
  done
done

Great video explaining bash arrays: Arrays in Bash Explained in 7 Minutes! - Indexed, Associative, and Nested / Multi-Dimensional - YouTube