This tutorial will help you to create an Array in bash script. Also, initialize an array, add an element, update element and delete an element in the bash script.

Define An Array in Bash

You have two ways to create a new array in bash script. The first one is to use declare command to define an Array. This command will define an associative array named test_array. In another way, you can simply create Array by assigning elements.

Access Array Elements

Similar to other programming languages, Bash array elements can be accessed using index number starts from 0 then 1,2,3…n. This will work with the associative array which index numbers are numeric. To print all elements of an Array using @ or * instead of the specific index number.

Loop through an Array

You can also access the Array elements using the loop in the bash script. A loop is useful for traversing to all array elements one by one and perform some operations on it.

Adding New Elements to Array

You can add any number of more elements to existing array using (+=) operating. You just need to add new elements like: View the array elements after adding new:

Update Array Elements

To update the array element, simply assign any new value to the existing array by the index. Let’s change the current array element at index 2 with grapes. View the array elements after adding new:

Delete An Array Element

You can simply remove any array elements by using the index number. To remove an element at index 2 from an array in bash script. View the array elements after adding new: