Create and Use Array in Bash Script

Linux

An array is a data structure consist multiple elements based on key pair basis. Each array element is accessible via a key index number.

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.

declare -a test_array

In another way, you can simply create Array by assigning elements.

test_array=(apple orange lemon)

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.

echo $

apple

To print all elements of an Array using @ or * instead of specific index number.

echo $

apple orange lemon

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.

for i in $

do

echo $i

don

You can add any number of more elements to existing array using (+=) operating. You just need to add new elements like:Adding New Elements to Array

test_array+=(mango banana)

View the array elements after adding new:

echo $

apple orange lemon mango banana

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.

test_array[2]=grapes

View the array elements after adding new:

echo $

apple orange grapes mango banana

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.

unset test_array[2]

View the array elements after adding new:

echo $
apple orange mango banana

Source

Share: