Bash Array of Arrays [Explained]

The Bash arrays provide an effective way to store and work with data. This guide will discuss a particular array type, commonly known as a Bash array of arrays. It will improve your data organizing capability using arrays within arrays. I’ll also walk you through the necessary commands and syntax along with developing Bash scripts to solidify your understanding of  Bash array of arrays.

What is an Array of Arrays in Bash?

An array of arrays in Bash is a data structure where an array holds other arrays as elements. This creates a 2D array-like structure allowing for multidimensional data representation with rows and columns. Such an array is also called a 2D or multidimensional array.

However, it’s important to note that Bash doesn’t have “built-in support” for a direct array of arrays. This can only be simulated and we must come up with a way to declare and emulate this multidimensional array structure. Also, we have to smartly use array-based commands and expressions to access and manipulate such arrays.

2 Ways to Simulate an Array of Arrays in Bash

We can simulate a Bash array of arrays with some smart approaches. In this section, I’ll show you 2 effective ways (using nested arrays and associative arrays) to simulate an array of arrays using Bash scripts.

1. Using Bash Sub-Arrays

One approach to simulate a Bash array of arrays is to use independent subarrays within the main array imitating a nested array structure. It involves employing the general Bash array declaration syntax, 2D_array=(array1 array2.. arrayN), where the elements are arrays rather than single entities. Here’s an example:

#!/bin/bash 

ArrayOfArray_1=("Alan" "24")
ArrayOfArray_2=("Walker" "31")
MainArray=(
  ArrayOfArray_1[@]
  ArrayOfArray_2[@]
)

for sub_array in "${MainArray[@]}"; do
  elements=("${!sub_array}") # Get the elements of the sub-array
  name=${elements[0]}
  age=${elements[1]}
  echo "${name,,} $age" 
done
EXPLANATION

In this script, the MainArray contains elements that reference another 2 arrays ArrayOfArray_1=("Alan" "24") and ArrayOfArray_2=("Walker" "31"). Here, the syntax MainArray=( ArrayOfArray_1[@] ArrayOfArray_2[@]) smartly declares the 2D-like array in Bash. Finally, the loop for sub_array in "${MainArray[@]}" takes each subarray and prints the values achieving a multidimensional structure by taking into account the array elements using the expressions name=${elements[0]} and age=${elements[1]}.

simulate bash array of arrays with nested arraysHere, 2 subarrays form a 2D-like format to simulate the Bash array of arrays.

2. Using Associative Arrays in Bash

Bash associative arrays (Hashes) are specialized arrays that store data value using a string index or key. Now, the declaration syntax declare -A <associative_array> along with the Bash nested for loops can declare an array of arrays in Bash. Here’s how:

#!/bin/bash

# Declare a basic Bash 2D array using associative array
declare -A two_d_array

# Assign values to the 2D array using keys
two_d_array[0,0]="1"
two_d_array[0,1]="2"
two_d_array[1,0]="3"
two_d_array[1,1]="4"

# Get the dimensions of the 2D array
rows=2
cols=2

# Loop through the rows and columns to print the elements
for ((i = 0; i < rows; i++)); do
    for ((j = 0; j < cols; j++)); do
        echo -n "${two_d_array[$i,$j]} "  # Print each element with a space
    done
    echo  # Move to the next line after printing a row
done
EXPLANATION

In this Bash script above, the declare -A two_d_array command first creates an associative array assigns 4 values, and defines 2 rows and 2 columns to mimic the 2D array. After that the for loop for ((i = 0; i < rows; i++)) iterates over the columns and the nested for loop for ((j = 0; j < cols; j++)) iterates over the columns and echo -n "${two_d_array[$i,$j]} " prints the elements 1 and 2  in a row. Then the echo command moves to the next line; similarly, elements 3 and 4 are printed in the 2nd row.  

simulate array of arrays with Bash associative arraysSee from the image, the Bash associative array is printed in the array of arrays (2D) format.

Access an Array of Arrays in Bash

Accessing a Bash array of arrays is to navigate through the main array that contains elements such as arrays or strings representing subarrays. In this section, I’ll show you how to access the array by adding new elements, updating elements, and removing the entire array.

1. Add Array Elements in Bash

To add elements to the simulated structure of the Bash array of arrays, you can use the appending syntax, array+=(element to add) where the element would be a string representation achieving a subarray format that adds a new element to the end of the array by default.

See the following example to understand how it works:

# Declaration of an array of arrays (as strings)
array_of_arrays=(
    "1 2 3"   # Sub-array 1 represented as a string
    "4 5 6"   # Sub-array 2 represented as a string
    "7 8 9"   # Sub-array 3 represented as a string
)

echo "before:"
# print array before appending 
for sub_array_str in "${array_of_arrays[@]}"; do
    sub_array=($sub_array_str)
    echo "${sub_array[*]}"  # Print the elements of each sub-array
done

#add  new elements 
array_of_arrays+=("3 4 5")

echo "after:"

# Loop through the array and split each element into individual elements for display
for sub_array_str in "${array_of_arrays[@]}"; do
    sub_array=($sub_array_str)
    echo "${sub_array[*]}"  # Print the elements of each sub-array
done
EXPLANATION

Here, after declaring array_of_arrays, the expression array_of_arrays+=("3 4 5") adds the elements 3 4 5 to the end of the array emulating the 4th row. Then the for loop for sub_array_str in "${array_of_arrays[@]}" iterates over the subarrays and the command echo "${sub_array[*]}"   prints the elements in the multidimensional array format.

adding new elements in the 2d arrayThe expression array_of_arrays+=(“3 4 5”)  adds a new row of elements at the end of the array

2. Update Array Elements

To update the content of the array of arrays structure, assign new values by using its index to access a row and update either all the elements or a specific element. The typical syntax is 2d_array[index]= updated_value. For instance, the expression array_of_arrays[0]="1 3" will update the entire row of array_of_arrays with the updated values “1 3”.

Here’s a complete example of updating the contents of the array named array_of_arrays using the syntax array_of_arrays[0]="1 1 1":

#!/bin/bash
array_of_arrays=(
    "1 2 3"   # Sub-array 1 represented as a string
    "4 5 6"   # Sub-array 2 represented as a string
    "7 8 9"   # Sub-array 3 represented as a string
)

# Update an element (update the first element of the third sub-array)
array_of_arrays[0]="1 1 1"  # Reassigning the value at index 2 to update the first element

# Show the updated array
for sub_array_str in "${array_of_arrays[@]}"; do
    sub_array=($sub_array_str)
    echo "${sub_array[*]}"  # Print the updated elements of each sub-array
done
EXPLANATION

In the above, array_of_arrays has 9 elements in the 2D-like format. The command array_of_arrays[0]=”1 1 1″ updates the 2nd and 3rd previous values (2 3) of the 1st string subarray to 1 1.

update array elementsThe elements of the 1st subarray are replaced with updated elements.

3. Remove Array of Arrays in Bash

Removing a Bash array of arrays is very simple. Use the unset command and mention the array name afterward to delete the 2D array-like structure from the system. The syntax is unset <array_name>.

Here’s an example to remove the 2D array named array_of_arrays using the syntax unset array_of_arrays:

#!/bin/bash

#the array of arrays
array_of_arrays=(
    "1 2 3"   
    "4 5 6"   
    "7 8 9"  
)

echo "before:"

# print the array before delete
for sub_array_str in "${array_of_arrays[@]}"; do
    sub_array=($sub_array_str)
    echo "${sub_array[*]}"  # Print the updated elements of each sub-array
done
#remove the array with all the elements using unset command
unset array_of_arrays

echo "after deleting:"

#print the array again to get an empty prompt
echo "${array_of_arrays[@]}"
EXPLANATION

Here, after the simulation of the bash multidimensional array using a string representation, the echo command along with the for loop prints the array. After that, the command unset array_of_arrays removes the array with its elements. That’s why the final command echo "${array_of_arrays[@]}" returns an empty prompt. This indicates that the array no longer exists. 

remove arrayThe unset command deletes a Bash 2D array and the echo command prints nothing on the prompt.

Conclusion

In this tutorial, I have discussed the ins and outs of the Bash array of arrays. I have also walked you through the essential syntax with Bash script development to gain a hands-on understanding of simulating and modifying the array. Hope it helps you to comprehend the concepts of multidimensional arrays in Bash for data handling beyond the general approaches. Happy scripting!

People Also Ask

What is a Bash array?

A Bash array is a data structure used to store information in an indexed way. The indexed array in Bash has numbered indices while the associative arrays have string indices called keys. Unlike other programming languages, Bash arrays can store elements of various data types.

Does Bash have 2D arrays?

No, Bash doesn’t natively support 2D arrays but we can simulate its multidimensionality using string representation or adding arrays as elements within a single array. This involves the use of nested for loops in Bash to represent rows and columns.

How can I iterate through a Bash 2D array?

Use nested for loops that iterate through the main array and then over the subarray structures to access the elements. Moreover, you can use this method to print the array. Here’s how:

#!/bin/bash

#the array of arrays
identity=(
    "1 1 1"   
    "1 1 1"   
    "1 1 1"  
)
# iterate over the array of arrays called identity
for sub_array_str in "${identity[@]}"; do
    sub_array=($sub_array_str)
    echo "${sub_array[*]}"  # Print the updated elements of each sub-array
done

Output:

1 1 1

1 1 1

1 1 1

Can I print the elements of a Bash 2D array in a single line?

Yes, you can. Use the length expression syntax echo "${2D_array[@]}" to print the elements of 2D_array  in a single line. Here’s an example:

#!/bin/bash
#array of arrays
matrix=(
    "1 2 3"   
    "4 5 6"   
    "7 8 9"  
)
#print elements in a single line 
echo "${matrix[@]}"

Output:

1 2 3 4 5 6 7 8 9

Can I read a 2d array in Bash?

Yes, you can. Use the readarray command to read a 2D array in Bash with contents from a file. Look at the following example to read a 2D array in Bash from a file called file.txt:

#!/bin/bash
# Read lines from a file into the array
readarray -t lines < file.txt
# Declare array
declare -A array
# Iterate over the lines and split each line into elements
for i in "${!lines[@]}"; do
  IFS=' ' read -r -a elements <<< "${lines[i]}"
  for j in "${!elements[@]}"; do
    if [[ -n "${elements[j]}" ]]; then
      array[$i,$j]=${elements[j]}
    fi
  done
done
# Print the array
for ((i=0;i<3;i++)); do
  for ((j=0;j<3;j++)); do
    echo -n "${array[$i,$j]} "
  done
  echo
done

file.txt contents:

1 2 3

4 5 6

7 8 9

Script Output:

1 2 3

4 5 6

7 8 9

Are Bash multidimensional arrays useful for handling large-scale data?

No, such arrays are not the most suitable in terms of handling large-scale data due to their limitations in working with complex data structures. For this extensive purpose, adopting tools from other programming languages might be effective.

Related Articles


<< Go Back to Bash Array | Bash Scripting Tutorial

3.3/5 - (3 votes)
Md Masrur Ul Alam

Assalamu Alaikum, I’m Md Masrur Ul Alam, currently working as a Linux OS Content Developer Executive at SOFTEKO. I completed my Bachelor's degree in Electronics and Communication Engineering (ECE)from Khulna University of Engineering & Technology (KUET). With an inquisitive mind, I have always had a keen eye for Science and Technolgy based research and education. I strongly hope this entity leverages the success of my effort in developing engaging yet seasoned content on Linux and contributing to the wealth of technical knowledge. Read Full Bio

Leave a Comment