Working with Arrays in Bash

11 min read·Feb 24, 2025

As a reminder, an array is a type of variable that contains a collection of data organized into a list or sequence.

Arrays are declared using parenthesis () and each element within it is separated by a space character.

array=(element1 ... elementN)

Accessing array elements

When declaring an array, each of its elements (or values) is automatically associated with a unique numerical position called an index, where the first element is stored at index 0, the second at index 1, and so on.

To access and use the value stored at a specific index, you can use this syntax:

${array[index]}

Where:

  • array is the name of the variable containing the array.
  • index is the index you want to access the value of.

On the other hand, to access all the values of an array at once, separated by a single space character, you can use the special @ index:

${array[@]}

Example

Let's consider this directory:

$ ls
index.js	package.json	script.sh

Let's consider this script, that outputs the name of the files present in this directory:

#!/bin/bash

output=$(ls)
files=($output)

echo "1st filename: ${files[0]}"
echo "2nd filename: ${files[1]}"
echo "3rd filename: ${files[2]}"
echo "All filenames: ${files[@]}"

When executed, it will:

  1. Define a variable named output and initialize it with the output of the ls command.
  2. Define a variable named files and initialize it with the value of the output variable converted to an array of strings.
  3. Output the 1st, 2nd, and 3rd element of the files array at index 0, 1, and 2.
  4. Output all the elements of the files array.

Which will produce this output:

$ ./script.sh
1st filename: index.js
2nd filename: package.json
3rd filename: script.sh
All filenames: index.js package.json script.sh

Extracting array elements

To extract a subset of an array, you can use this syntax:

subset=(${array[@]:start:length})

Where:

  • () is used to create a new array.
  • start is the index of the first element to extract.
  • length is the number of elements to extract from the start index.

Example

Let's consider this script, that extracts and outputs the elements of an array separately:

#!/bin/bash

location=("Arc de Triomphe" "Pl. Charles de Gaulle" 75008 "Paris" "France" "48.8738N" "2.2950E")

name=${location[0]}
address=(${location[@]:1:4})
coordinates=(${location[@]:5:2})

echo "Name = $name"
echo "Address = ${address[@]}"
echo "Coordinates = ${coordinates[@]}"

When executed, it will:

  1. Declare an array named location and initialize it with 7 elements.
  2. Declare a variable named name and initialize it with the element at index 0 of the location array.
  3. Declare a variable named address and initialize it with a subset of the location array going from index 1 to 4.
  4. Declare a variable named coordinates and initialize it with a subset of the location array going from index 5 to 7.
  5. Output the values of the name, address, and coordinates variables.

Which will produce this output:

$ ./script.sh
Name = Arc de Triomphe
Address = Pl. Charles de Gaulle 75008 Paris France
Coordinates = 48.8738N 2.2950E

Modifying array elements

To change the value of an array element, you can use the assignment operator =:

array[index]=new_value

Where:

  • array is the name of the variable holding the array.
  • index is the index you want to update in the specified array.
  • new_value is the new value you want to assign to the specified index.

Example

Let's consider this script, that a creates a configuration file named identity containing a username and a password:

#!/bin/bash

credentials=("username=" "password=")

credentials[0]="${credentials[0]}$1"
credentials[1]="${credentials[1]}$2"

echo ${credentials[@]} | tr ' ' '\n' > identity.txt

When executed, it will:

  1. Declare an array named credentials and initialize it with two strings.
  2. Update the value of the 1st element at index 0 of the credentials array by concatenating its current value with the value of the 1st positional argument.
  3. Update the value of the 2nd element at index 1 of the credentials array by concatenating its current value with the value of the 2nd positional argument.
  4. Write the values of the credentials array into the identity.txt file.

Which will produce this output:

$ ./script.sh
$ cat identity.txt
username=
password=
$ ./script.sh johndoe helloworld
$ cat identity.txt
username=johndoe
password=helloworld

Appending values to arrays

To append additional values to an existing array, you can use the += operator and specify these values in parenthesis () as follows:

array+=(value ...)

Note: The additional values will start at the last index + 1.

Example

Let's consider this script, that appends the value of positional arguments to an array:

#!/bin/bash

config=("username=admin" "password=admin")
config+=($@)

echo ${config[@]} | tr ' ' '\n' > profile

When executed, it will:

  1. Declare an array named config and initialize it with two strings.
  2. Append the value of all the positional arguments of the script to the config array.
  3. Write the values of the config array into the profile.txt file.

Which will produce this output:

$ ./script.sh
$ cat profile.txt
username=admin
password=admin
$ ./script.sh 'first_name=John' 'last_name=Doe' 'email_address=johndoe@mail.com'
$ cat profile.txt
username=admin
password=admin
first_name=John
last_name=Doe
email_address=johndoe@mail.com

Removing values from arrays

To remove the value of an array at a specific index, you can use the unset command:

unset array[index]

Notes:

  • This command doesn't change or shift the other array indexes.

  • This command has no effect on read-only arrays.

Copying arrays

To create an identical copy of an array, you can use this syntax:

copy=("${array[@]}")

Where:

  • () is used to create an array.
  • ${array[@]} is used to access all the values of an array at once.

Summary

Here's a summary of what you've learned in this lesson:

  • The ${array[index]} syntax is used to access an array's index value.
  • The ${#array[@]} syntax is used to access all the values of an array, separated by a single space character.
  • The array[index]=new_value syntax is used to reassign the value of an existing array's index.
  • The array+=(value ...) syntax is used to append new values to an existing array.
  • The (${array[@]:start:length}) syntax is used to extract a subset of an array.
  • The ("${array[@]}") syntax is used to create a copy of an array.
  • The unset command is used to delete array indexes.

Enjoying the courses?

I've made these courses completely free so anyone can learn from them. If they've helped you and you'd like to actively support the work behind BackendBrewery, you can leave a tip:

Support BackendBrewery
Working With Arrays in Bash | Backend Brewery