How to Use Bash Arrays

Introduction

Before we begin talking about how to use bash arrays, let's briefly understand – What is an Array ?

An array is a fundamental concept in programming. It is a data structure that allows you to store multiple values under a single name. Essentially, it is like a container that can hold various elements like numbers, strings, or even objects. With arrays, you can easily organize and manipulate collections of data.

They are widely used for tasks like sorting, searching, and grouping information efficiently. Arrays play a crucial role in many programming languages and are essential for developing robust software solutions. Understanding arrays is fundamental for any aspiring programmer or developer.

In this tutorial, you will use bash arrays. We will also address a few FAQs on how to use bash arrays.

Advantages of Array

  1. Efficient Storage: Arrays provide a way to store and access multiple values using a single variable, saving memory and making data organization easier.
  2. Quick Access: With arrays, you can directly access any element using its index, allowing for fast retrieval and manipulation of data.
  3. Easy Sorting: Arrays enable straightforward sorting of elements. This makes arranging data in ascending or descending order a breeze.
  4. Seamless Iteration: Array elements can be easily looped through, simplifying tasks like calculations, comparisons, or performing operations on each element.
  5. Versatility: Arrays can store various data types, including numbers, characters, and objects. This flexibility allows for diverse programming applications and solutions.

Bash Arrays

One-dimensional numerically indexed and associative arrays are supported by Bash. Integers are used to refer to numerical arrays, while strings are used to refer to associative arrays.

Negative indices can be used to access numerically indexed arrays from the end; the index of -1 refers to the last element. The indices don't have to be in any particular order.

Unlike other programming languages, the components of a Bash array do not have to be of the same data type. You can make an array with both strings and integers in it.

Multidimensional arrays are not supported in Bash, and array elements that are also arrays are not allowed.

The greatest number of elements that can be stored in an array is unlimited.

Creating Bash Arrays

In Bash, arrays can be started in a variety of ways.

Creating numerically indexed arrays

Because Bash variables are untyped, they can be used as indexed arrays without having to declare them.

Use the declare built-in to declare an array explicitly:

declare -a array_name

The following is an example of how to make an indexed array:

array_name[index_1]=value_1
array_name[index_2]=value_2
array_name[index_n]=value_n

In this case, index_* is a positive number.

Another technique to make a numeric array is to put the components in parenthesis and divide them with empty space:

array_name=( element_1 element_2 element_N )

The indexing starts at zero when the array is generated using the method above, therefore the first member has an index of 0.

Creating associative arrays

As opposed to numerically indexed arrays, associative arrays must be declared before being utilized.

Use the declare built-in with the -A (uppercase) option to declare an associative array:

declare -A array_name

The following formula can be used to build associative arrays:

declare -A array_name

array_name[index_foo]=value_foo
array_name[index_bar]=value_bar
array_name[index_xyz]=value_xyz

Any string can be used as index_*.

You may also use the form below to make an associative array:

declare -A array_name

array_name=( 
  [index_foo]=value_foo 
  [index_bar]=value_bar 
  [index_xyz]=value_xyz 
)

Array Operations

The syntax of Bash arrays may appear unusual at first, but after reading this tutorial, it will make more sense.

Reference Elements

The element index is required to refer to a single element.

The following syntax can be used to refer to any element:

${array_name[index]}
ℹ️
Accessing an array element uses syntax that is comparable to that of most computer languages. To circumvent the shell's filename expansion operators, ${} are required.

Let's see what happens if we print the first element:

## declare the array
declare -a my_array=( "Hydrogen" "Helium" "Lithium" "Beryllium" )

## print element
echo ${my_array[1]}
Output

Helium

When you use @ or * as an index, the term expands to include all array members. To print all of the elements, you'd use:

## declare the array
declare -a my_array=( "Hydrogen" "Helium" "Lithium" "Beryllium" )

## print all elements
echo "${my_array[@]}"
Output

Hydrogen Helium Lithium Beryllium

The only time @ and * differ is when the form ${my_array[x]} is enclosed in double-quotes. In this scenario, * extends to a single word with space between array components. Each array element is expanded to a separate word with @. When using the form to illiterate through array elements, this is extremely crucial.

Add the ! operator before the array name to print the array's keys:

${!array_name[index]}

Here is an example:

## declare the array
declare -a my_array=( "Hydrogen" "Helium" "Lithium" "Beryllium" )

## print all elements
echo "${!my_array[@]}"
Output

0 1 2 3

Array Length

Use the following syntax to determine the length of an array:

${#array_name[@]}
ℹ️
With the inclusion of the # character before the array name, the syntax is the same as when referring all elements.
## declare the array
declare -a my_array=( "Hydrogen" "Helium" "Lithium" "Beryllium" )

## array Length
echo ${#my_array[@]}
Output

4

Loop through the array

The for loop is the most popular approach to iterate through each item in an array:

declare -a my_array=( "Hydrogen" "Helium" "Lithium" "Beryllium" )

## Array Loop
for i in "${my_array[@]}"
do 
  echo "$i"
done

The following code iterates through the array, printing each element on a new line:

Output

Hydrogen
Helium
Lithium
Beryllium

An example of how to print all keys and values is as follows:

declare -a my_array=( "Hydrogen" "Helium" "Lithium" "Beryllium" )

## Array Loop
for i in "${!my_array[@]}"
do
  echo "$i" "${my_array[$i]}"
done
Output

0 Hydrogen
1 Helium
2 Lithium
3 Beryllium

Another option for looping through an array is to obtain the array's length and use the C style loop:

declare -a my_array=( "Hydrogen" "Helium" "Lithium" "Beryllium" )

# Length of the array
length=${#my_array[@]}

# Array Loop
for (( i=0; i < ${length}; i++ ))
do
  echo $i ${my_array[$i]}
done
Output

0 Hydrogen
1 Helium
2 Lithium
3 Beryllium

Add a new element

Use the following syntax to add a new element to a bash array and provide its index:

my_array[index_n]="New Element"

Here's an example:

declare -a my_array=( "Hydrogen" "Helium" "Lithium" "Beryllium" )

## add new element
my_array[9]="Aluminum"

## print all elements
echo "${my_array[@]}"
Output

Hydrogen Helium Lithium Beryllium Aluminum

The += operator is another way to add a new element to an array without specifying the index. You can include one or more elements:

declare -a my_array=( "Hydrogen" "Helium" "Lithium" "Beryllium" )

## add new elements
my_array+=( Cobalt Nickel )

## print all elements
echo "${my_array[@]}"
Output

Hydrogen Helium Lithium Beryllium Cobalt Nickel

Delete an element

You'll need to know the element index to delete a single element. The unset command can be used to remove an element:

unset my_array[index]

Let’s see an example:

declare -a my_array=( "Hydrogen" "Helium" "Lithium" "Beryllium" )

## remove element
unset my_array[2]

## print all elements
echo "${my_array[@]}"
Output

Hydrogen Helium Beryllium

FAQs to Use Bash Arrays

Can I iterate over a Bash array? 

Yes, you can iterate over a Bash array using a loop. One common approach is the for loop, iterating over the array indices or elements.

How do I get the length of a Bash array? 

To determine the length of an array, use the syntax ${#array_name[@]}. This returns the number of elements in the array.

How do I add elements to a Bash array? 

To add elements, you can use the syntax array_name+=(new_element) or array_name[index]=new_element. For instance, my_array+=(grape).

Can I sort a Bash array? 

Yes, you can sort a Bash array using the sort command with appropriate options. For example, sorted_array=($(printf "%s\n" "${my_array[@]}" | sort)) creates a sorted array.

How can I delete an element from a Bash array?

To delete an element, use the unset command followed by the array variable and index. For example, unset my_array[2] removes the third element.

What is the difference between indexed and associative Bash arrays? 

Indexed arrays are accessed via numerical indices, starting from zero. Associative arrays use custom keys instead of indices, like associative mapping.

What is the difference between indexed and associative Bash arrays? 

Indexed arrays are accessed via numerical indices, starting from zero. Associative arrays use custom keys instead of indices, like associative mapping.

Conclusion

We've covered how to make associative and numerically indexed arrays. We've also demonstrated how to cycle across the arrays, compute the length of the array, and add and remove elements.

If you have any queries, please leave a comment below and we’ll be happy to respond to them.