How to use arrays in Bash

9 feb 2024 4 min di lettura
How to use arrays in Bash
Indice dei contenuti

Introduction

Arrays are one of the most used and fundamental data structures. You can think of an array as a variable that stores multiple variables within it. Arrays offer a convenient way to represent and manipulate a group of related data items as a single entity.

In this article we will cover Bash arrays and explain how to use them in your Bash scripts.

Array Bash

Bash supports one-dimensional associative and numerically indexed array types. Numeric arrays are referenced using integers and associative using strings.

Numerically indexed arrays can be accessed from the end using negative indices; the index of -1 references to the last element. Indexes do not have to be contiguous.

Unlike most programming languages, Bash array elements do not have to be of the same data type. This means you can create an array containing both strings and numbers.

Bash does not support multidimensional arrays, and it is not possible to have array elements that are also arrays.

There is no limit to the maximum number of elements that can be stored in an array.

Creating Bash arrays

In Bash, arrays can be initialized using several methods.

Creating numerically indexed arrays

Bash variables are not typed. Any variable can be used as an indexed array without declaring it.

To explicitly declare an array, use the declare builtin command:

declare -a array_name

One way to create an indexed array is to use the following form:

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

Where index_* is a positive integer.

Another way to create a numeric array is to specify the list of elements in parentheses, separated by white space:

array_name=( element_1 element_2 element_N )

When the array is created using the previous form, indexing starts from zero, that is, the first element has an index of 0.

Creating associative arrays

Associative arrays are a type of array in which each element is identified by a unique key rather than an index.

Unlike numerically indexed indices, associative arrays must be declared before they can be used.

To declare an associative array, use the declare built-in with the -A (uppercase) option:

declare -A array_name

Associative arrays are created using the following form:

declare -A array_name

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

Where index_* can be any string.

You can also create an associative array using the following form:

declare -A array_name

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

Array operations

If you're new to Bash programming, arrays in Bash can be confusing at first. However, after reading this article, you will understand them better.

Reference elements

To reference a single element, you need to know the index of the element.

You can refer to any element using the following syntax:

${array_name[index]}

The syntax for accessing an array element is similar to the syntax of most programming languages. The curly braces ${} are needed to avoid the shell's filename expansion operators.

We print the element with an index of 1:

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

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

If you use @ or * as an index, the word expands to all members of the array.

To print all items, you should use:

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

 ## print all elements
 echo "${my_array[@]}"
Hydrogen Helium Lithium Beryllium

The only difference between @ and * is when the form ${my_array[x]} is enclosed in double quotes. In this case, * expands to a single word where the array elements are separated by a space. @ expands each element of the array into a separate word. This is especially important when using the illiterate form through array elements.

To print the array keys, add the ! operator before the array name:

${!array_name[index]}

Here is an example:

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

 ## print all elements
 echo "${!my_array[@]}"
0 1 2 3

Length of the matrix

If you want to determine the number of elements in an array, you can use the following syntax to get the length of the array:

${#array_name[@]}

The syntax is the same as when referencing all elements by adding the # character before the array name.

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

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

Go through the array

When you have a set of items, you often need to perform an operation on each item. One way to achieve this is to iterate over the array using a loop. The for loop allows you to access each element of the array individually and perform the desired operation on it.

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

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

The code above will iterate over the array and print each element in a new line:

Hydrogen
 Helium
 Lithium
 Beryllium

Here is an example of how to print all keys and values:

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

 ## Array Loop
 for i in "${!my_array[@]}"
 do
 echo "$i" "${my_array[$i]}"
 done
0 Hydrogen
 1 Helium
 2 Lithium
 3 Beryllium

Another way to iterate through an array is to get the length of the array 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
0 Hydrogen
 1 Helium
 2 Lithium
 3 Beryllium

Adding a new item

To add a new element to a bash array and specify its index, use the following form:

my_array[index_n]="New Element"

Here is an example:

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

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

 ## print all elements
 echo "${my_array[@]}"
Hydrogen Helium Lithium Beryllium Aluminum

Another way to add a new element to an array without specifying the index is to use the += operator. You can add 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[@]}"
Hydrogen Helium Lithium Beryllium Cobalt Nickel

Delete an item

To delete a single item, you will need to know the index of the item. An element can be removed using the unset command:

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[@]}"
Hydrogen Helium Beryllium

Conclusion

We have explained how to create numerically indexed and associative arrays. We also showed how to iterate through arrays, calculate array length, and add and remove elements.

If you have any questions or feedback, feel free to leave a comment.

Support us with a

Successivamente, completa il checkout per l'accesso completo a Noviello.it.
Bentornato! Accesso eseguito correttamente.
Ti sei abbonato con successo a Noviello.it.
Successo! Il tuo account è completamente attivato, ora hai accesso a tutti i contenuti.
Operazione riuscita. Le tue informazioni di fatturazione sono state aggiornate.
La tua fatturazione non è stata aggiornata.