Arrays in bash allow you to store and access data efficiently by allowing you to access any element directly using its index. This is faster than searching several variables one by one. The arrays are very helpful in programming languages or scripting to store multiple data types that can be reused.
The bash scripts allow the user to automate several command line tasks in sequence. Automation needs several variables where the bash arrays are commonly used to store the data in an indexed way.
This guide will discuss the methods to initialize an array in bash and perform fundamental array functions using the following timeline:
- Types of Bash Arrays
- Declare an Array in Bash
- Access a Bash Array
- Add Elements to a Bash Array
- Delete Elements of a Bash Array
- Delete a Bash Array
- Loop Through Bash Arrays
- Different Uses of Bash Array
Let’s start with the types of arrays.
Types of Bash Arrays
Two types of arrays are used in bash shell scripts, which are as follows:
Indexed Array
The indexed arrays, as the name suggests, the variables can be accessed through their indexes, and the array index starts with 0.
Associative Array
The associative arrays are used as key-value pairs. The values in these arrays are mapped against their key.
How to Declare an Array in Bash?
The arrays store the data of several types, such as string, number, or variable. To create a simple array, the following syntax is used:
$ array-name=(array-elements)
- array-name: Replace it with the specific name of an array.
- array-elements: It is replaced with the array values.
To create or declare a bash array in Linux, two formats are used:
$ declare -a newArray=(Monday Tuesday 1 2)
Or we can declare an array using:
$ newArray=(Monday Tuesday 1 2)
Bothe formats will initialize an array.
How to Access a Bash Array?
In this section, we will understand the methods to access the elements of arrays with Bash scripts. The arrays can be used in bash scripts with the below methods:
array=() | To create an empty array. |
array=(a b c) | To create an array with 3 elements. |
${array[0]} | To get the first index value from the array. |
${array[@]} ${array[*]} | To get all the values from an array. |
${!array[@]} | It uses the array index to get the array elements. |
$array[0]=3 | Overwrite the first index of an array. |
unset $array[0] | It removes the first element of an array |
${#array[@]} | To calculate the array’s length. |
$array+=(2) | Append a value on the third index of an array. |
$array=( $(ls) ) | Save the “ls” command’s output in an array. |
${array[@]:0:4} | Retrieve values from the first to fifth index values. |
Note: We have used the array word as the name of the array, replacing the array with your desired array name.
The following array with array name “newArray” and bash script name “arrays.sh” will be used throughout this article:
myArray=(Monday Tuesday Wednesday Thursday Friday Saturday Sunday)
Example 1: Retrieve a Specific Element of Bash Array
Every array starts from index “0”, and we can easily retrieve an element from the array using the element index. For instance, an array named “newArray” is initialized, and to find its first index element, the following script is used:
#!/bin/bash
newArray=(Monday Tuesday Wednesday Thursday Friday Saturday Sunday)
echo "The first weekday is: ${newArray[0]}"
Run the above arrays bash script code:
$ bash arrays.sh
The output shows the first value (0 index) of the newArray is “Monday”.
Example 2: Retrieve All Elements of a Bash Array
All the array elements can be retrieved simultaneously by utilizing the below code:
#!/bin/bash
declare -a newArray=(Monday Tuesday Wednesday Thursday Friday Saturday Sunday)
echo "A week has: ${newArray[@]}"
Run the bash script with below command:
$ bash arrays.sh
The output shows all array elements are retrieved.
Similarly, to get an element of an array using the for loop, execute the below bash script:
#!/bin/bash
newArray=(Monday Tuesday Wednesday Thursday Friday Saturday Sunday)
for str in ${newArray[@]};
do
echo $str
done
To run the above script:
$ bash arrays.sh
The output displays for every loop execution.
Example 3: Retrieve Bash Array Elements Indexes
If you want to check the index of an element or the whole array, the ${!newArray[@]} syntax is used. For instance, t check the indexes of the whole array; the below code is utilized:
#!/bin/bash
newArray=(Monday Tuesday Wednesday Thursday Friday Saturday Sunday)
echo "The array indexes are: ${!newArray[@]}"
To run the code:
$ bash arrays.sh
The array index is quite useful in arrays and writing scripts, which gives dynamic elements on a specific index. Let’s use the index format in a for loop:
#!/bin/bash
declare -a newArray=(Monday Tuesday Wednesday Thursday Friday Saturday Sunday)
for i in ${!newArray[@]}; do
echo "element $i is ${newArray[$i]}"
done
Run the above index scripts:
$ bash arrays.sh
Every index and its value are displayed in the output.
Example 4: Retrieve Elements From Specific Index Range in Bash Array
If you want to get the elements of an array from one index to another the ${newArray[@]:start-index:end-index} format is used. For instance, to get the array elements from index 1 to index 4, use this code:
#!/bin/bash
newArray=(Monday Tuesday Wednesday Thursday Friday Saturday Sunday)
echo "The array values from 1st to 4th index are: ${newArray[@]:0:4}"
To execute the script, utilize:
$ bash arrays.sh
The elements from the 1st index to the 4th index are shown in the output.
Example 5: Overwrite a Specific Element in Bash Array
We can replace specific or multiple elements of an array. For instance, to replace the 1st element in an array, the below-mentioned code is executed:
#!/bin/bash
newArray=(Monday Tuesday Wednesday Thursday Friday Saturday Sunday)
newArray[0]=Friday
echo "The modified array is: ${newArray[@]}"
For running the script, execute this command:
$ bash arrays.sh
The 1st element is replaced with “Friday”.
How to Add Elements to a Bash Array?
The “+=” syntax adds an element at the last place in an array. To append the word “Monday” at the end of newArray, use the below-written code:
#!/bin/bash
newArray=(Monday Tuesday Wednesday Thursday Friday Saturday Sunday)
newArray+=(Monday)
echo "The modified array is: ${newArray[@]}"
To execute the bash script, use:
$ bash arrays.sh
The “Monday” element is appended at the end of the array.
How to Delete Elements of a Bash Array?
Sometimes, we need to delete a specific variable from the array; the below code is used to delete a single element (in this case, Tuesday) from the bash arrays:
#!/bin/bash
newArray=(Monday Tuesday Wednesday Thursday Friday Saturday Sunday)
delete=Tuesday
echo ${newArray[@]/$delete}
For running the script, execute this command:
$ bash arrays.sh
The output verifies that “Tuesday” is removed from the array.
Another way to delete an element from a specific array, we can use the “unset” command. For instance, to delete the 2nd element from the “newArray”, execute this code:
#!/bin/bash
newArray=(Monday Tuesday Wednesday Thursday Friday Saturday Sunday)
unset newArray[1]
echo "The modified array is: ${newArray[@]}"
For running the code:
$ bash arrays.sh
The 2nd element of the array “Tuesday” is deleted.
Similarly, we can delete more than one element of an array simultaneously using the for loop for that array. For instance, to remove two elements, “Tuesday” and “Thursday”, we can use the below-written script:
#!/bin/bash
newArray=(Monday Tuesday Wednesday Thursday Friday Saturday Sunday)
delete=(Tuesday Thursday)
for del in ${delete[@]}
do
newArray=("${newArray[@]/$del}")
done
echo ${newArray[@]/$delete}
For running the script, execute this command:
$ bash arrays.sh
“Tuesday” and “Thursday” are deleted from the array.
How to Delete a Bash Array?
The unset keyword is used to delete a bash array in Linux. The below script will delete the array “newArray” all elements, and the array will be deleted:
#! /bin/bash
newArray=(Monday Tuesday Wednesday Thursday Friday Saturday Sunday)
unset newArray
echo "newArray=($newArray)"
For running the code:
$ bash arrays.sh
The output displays that all the elements from the arrays are removed, and it is empty.
How to Loop Through Bash Arrays?
Different types of loops can be utilized with the bash arrays. These arrays allow the user to loop through every element of the array and provide a specific function on any element of the array.
Using For Loop With Bash Arrays
We can use the for loop with the bash arrays to print every element of the loop. For instance, the below script will show a single element for every loop iteration:
#!/bin/bash
newArray=(Monday Tuesday Wednesday Thursday Friday Saturday Sunday)
for i in "${newArray[@]}"
do
echo "$i"
done
For running the above script:
$ bash arrays.sh
The for loop prints each array element.
Using While Loop
The while loop is also utilized with the arrays to modify any array element. For instance, the below code will simply print every array element as we did previously with the for loop:
#!/bin/bash
newArray=(Monday Tuesday Wednesday Thursday Friday Saturday Sunday)
length=${#newArray[*]}
#iterate with while loop
i=0
while [ $i -lt $length ]
do
echo ${newArray[$i]}
i=$((i+1))
done
For running the above script, use:
$ bash arrays.sh
Every element of the array is printed.
Different Uses of Bash Arrays
We can use the bash arrays to calculate the array’s length and save the command’s output as an array.
Calculate Length of an Array in Bash
If you want to find out the total elements in an array, the “${#array-name[@]}” syntax is used. To find the length of “newArray”, run this code in the terminal:
#!/bin/bash
newArray=(Monday Tuesday Wednesday Thursday Friday Saturday Sunday)
echo "The length of the array is: ${#newArray[@]}"
To execute the code, use:
$ bash arrays.sh
The length of the newArray is 7.
Save a Command Output in an Array
The array can be used to save the output for a specific command. For instance, to save the “ls” command output to the newArray, the following code can be used in the bash shell:
#!/bin/bash
newArray=( $(ls) )
echo "The files array is: ${newArray[@]}"
To run the bash shell script:
$ bash arrays.sh
The list of files is saved in the newArray as seen in the output.
Conclusion
Bash arrays are used to store several types of data information, which can be used to perform desired operations in Linux. This guide discussed all the usage of the arrays in a Bash script, which includes declaring bash arrays, accessing, deleting, adding, and modifying elements of an array.