Arrays are a type of data structure that is used to store values of a certain type. You can also think array as a variable but a variable can only store one value where an array can store multiple values within it. The concept of the array is not only bound to bash. Any programming language you work with will have arrays in it but with implementation differences.
Bash supports two types of arrays:
- Indexed Array
- Associative Array
Indexed arrays are a type of array where elements (values) are stored and assigned with an integer number starting from 0 to N. The elements inside the array are referenced using the index number. You will get to know more about this in the upcoming article. The main focus of this article is only indexed arrays.
Table of Contents
How to initialize indexed array in Bash
The first step towards working with the array is to create it. The term create, define, initialize an array will be used interchangeably, but points to the same meaning - creating the array.
To create an array, you should use brackets and place the array elements (values) inside the brackets.
$ arr1=( one 2 three 4 )
Important points to note:
- Bash arrays can store elements of a different data type. In some programming languages, you can store values in an array of the same type only.
- There are no limitations on how many elements can be stored in the array. It depends on the availability of your system memory.
You can also use declare
command with the -a
flag to create an indexed array.
$ declare -a arr1
$ arr1=( one 2 three 4 )
Or,
$ declare -a arr1=( one 2 three 4 )
How to add or view elements of an array
You can either create an array with values in it like as shown in the previous section or just create an empty array and add values later. Below is how you create an empty array.
$ locations=()
Each element in an array has an associated index value starting from 0 to N. You have to add new elements to an array using the index position.
$ locations[0]="Chennai"
$ locations[1]="Mumbai"
Here is the graphical illustration of adding elements to an array.
To view the elements in an array, you can use either of the following syntaxes.
$ echo ${locations[@]}
$ echo ${locations[*]}
To know the difference between @ and * and how it works with array, refer the section "Loop over array elements" in our Bash For Loop guide.
If you try to list the array elements without using @
or *
only the first element in the array will be printed.
$ echo ${locations}
You can access a particular element directly using its index position.
$ echo ${locations[1]}
Index value of an array
In the previous section, I have shown how to add elements in an array using the index position. When you add arrays using index positions, you can skip and add elements to the different index positions.
The array locations have two elements in positions 0 and 1. Now I can skip index 2 and add to the different index positions.
$ locations[5]="Delhi"
From the above image, you can see I have added a new element to the array at the index position 5.
If you want to print the index values of elements, prefix the array with the "!"
symbol like below:
$ echo ${!locations[@]}
This will only print the index values Instead of printing the elements.
To print both index and elements, use the following snippet.
for val in ${!locations[@]} do echo "index = ${val} , value = ${locations[$val]}" done
Append values to an Array
You can add new elements to an array without using their index values and this will append elements to the array.
locations=( Chennai Mumbai Delhi ) locations+=( Bangalore ) locations+=( Hyderabad )
$ echo ${locations[@]}
$ echo ${!locations[@]}
Find length of an array
You can get how many elements are there in an array by prefixing the #
symbol before the array.
$ echo ${#locations[@]}
Using the same #
symbol, you can also find if the array is empty or not.
if [[ ${#locations[@]} -ne 0 ]]; then echo "Array is Not empty" else echo "Array is Empty" fi
Remove elements from an array
To remove an element from the array, you can use the unset
command. Take a look at the below example where using the unset
command the element from the index(2)
is removed.
$ echo ${locations[@]}
$ unset locations[2]
$ echo ${locations[@]}
Remove an array
To remove the array, you can use the same unset
command.
$ unset locations
$ echo ${locations[@]}
Empty an array
Sometimes you may wish to remove all the elements from the array and keep the array empty. In that case, you can simply recreate the array.
$ echo ${locations[@]}
Chennai Mumbai Delhi Hyderabad Bangalore
$ locations=()
$ echo ${locations[@]}
Store command output as array
You can run any commands and try to store the output in an array. The command should be enclosed with brackets for the output to be stored as an array.
$ path_list=( $(echo $PATH | tr ":" "\n") )
$ echo ${path_list[@]}
Array slicing
Slicing gives you the flexibility to pull out certain elements of the array based on their index position.
Following is the syntax for slicing:
${locations[@]:index:length}
If you wish to grab all the elements but from a particular starting index position, you can do it in the following way by using the index alone.
$ echo ${locations[@]:index} # syntax
$ echo ${locations[@]:2}
In the above example, the array will be printed starting from Index position 2 and till the last element. If you specify the length along with the index, then it will use the following formula to slice the array.
From index to index+length-1 (inclusive) # Formula
$ echo ${locations[@]:1:3}
If you skip the index and give length alone then it will slice using the following formula.
From Index 0 to length-1 (inclusive)
$ echo ${locations[@]::4}
Conclusion
In this article, I have walked you through the bash indexed array. Arrays are very important when you start writing complex bash scripts. They gives you the ability to store, retrieve and manipulate data of different type easily. Unlike programming languages like python, there are no built-in ways to use arrays easily to perform some complex tasks but still achievable.
In our next guide, we will discuss about Associative array in detail.
2 comments
Thanks man! I just love bash programming. This is a huge powerful language. I’ve being away from IT few years now, but I’m coming back and this kind of article reminds me how much I love this f…ing bash. It rocks!
Thanks again!
You’re welcome. We have also published a few more guides on Bash scripting. Please take a look here -> https://ostechnix.com/category/bash/bash-scripting/