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:
arrayis the name of the variable containing the array.indexis 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:
- Define a variable named
outputand initialize it with the output of thelscommand. - Define a variable named
filesand initialize it with the value of theoutputvariable converted to an array of strings. - Output the 1st, 2nd, and 3rd element of the
filesarray at index0,1, and2. - Output all the elements of the
filesarray.
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.startis the index of the first element to extract.lengthis the number of elements to extract from thestartindex.
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:
- Declare an array named
locationand initialize it with 7 elements. - Declare a variable named
nameand initialize it with the element at index0of thelocationarray. - Declare a variable named
addressand initialize it with a subset of thelocationarray going from index1to4. - Declare a variable named
coordinatesand initialize it with a subset of thelocationarray going from index5to7. - Output the values of the
name,address, andcoordinatesvariables.
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:
arrayis the name of the variable holding the array.indexis the index you want to update in the specified array.new_valueis 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:
- Declare an array named
credentialsand initialize it with two strings. - Update the value of the 1st element at index
0of thecredentialsarray by concatenating its current value with the value of the 1st positional argument. - Update the value of the 2nd element at index
1of thecredentialsarray by concatenating its current value with the value of the 2nd positional argument. - Write the values of the
credentialsarray into theidentity.txtfile.
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:
- Declare an array named
configand initialize it with two strings. - Append the value of all the positional arguments of the script to the
configarray. - Write the values of the
configarray into theprofile.txtfile.
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_valuesyntax 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
unsetcommand 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