Bash Indexed Array – Explained With Examples

The “Bash Indexed” array is a type of array that stores the elements (both string and integer) with an assigned integer starting from “0”. The elements in an array may be of different types, either string or integer. All the “Bash Indexed” array elements are referenced with an “index”. It is useful for storing and manipulating the elements in a specific order and also managing them. 

This guide illustrates the Bash Indexed array with different examples in Linux.

  • How Does the Bash Indexed Array Work in Linux?
  • Initialize an Indexed Array
  • Print an Indexed Array
  • Print Index Value
  • Append Array Values
  • Update an Indexed Array
  • Iterate an Indexed Array Through Loop
  • Length of Indexed Array
  • Indexed Array Slicing
  • Remove an Array
  • Remove Particular Array Element 

How Does the Bash Indexed Array Work in Linux?

The bash indexed array is a one-dimensional array having integer values or strings at the specified indexed position starting from zero “0”. The generalized syntax of the bash indexed array is stated below:

General Syntax:

ARRAY_NAME[index_1]=value_1 
ARRAY_NAME[index_2]=value_2 
ARRAY_NAME[index_n]=value_n

The “ARRAY_NAME” defines an array at the referenced position “[index]” having a specified value of integer or string.

Compound Syntax:

The bash indexed array can also be declared in one line having a set of values in this way:

$ ARRAY_NAME=(1,2,3,4…N )

Explicit Declaration of an Array:

The bash index array can be declared as a variable with the help of the “declare” command having data type “a(array)”:

$ declare -a ARRAY_NAME                           # Declare as a Variable
$ ARRAY_NAME=(1,2,3,4…N )                         # Defines Array Values

Let’s use above syntax to initialize an array:

Example 1: Initialize an Indexed Array

Create an array named “my_arr” starting from “0” index having string values simultaneously:

$ my_arr[0]=Linux
$ my_arr[1]=Ubuntu
$ my_arr[2]=RHEL
$ my_arr[3]=CentOS

The “my_arr” has been initialized having four index values.

Example 2: Print Specific Index Value

To print the array value placed at the specified index as “3”, use the “echo” command followed by the array name and the index in this way:

$ echo ${my_arr[3]}

The value of my_array at the third index has been printed on the terminal.

Example 3: Print Each Value of Array

The user can pass the “@” symbol at the indexed position for printing all the values of an array in the terminal:

$ echo ${my_arr[@]}

All the values of “my_array” have been printed in the terminal in the form of output. 

Example 4: Print Index Value

To print the index integer value then, use the “!(exclamation)” mark before the array name in this format:

$ echo ${!my_arr[@]}

The output contains all the index values of “my_arr”, not their content.

Note: For more details, read our guide on “How to Use Array in sh Script to Print All Values in Array”.

Example 5: Append Array Values

Once the array is declared, it can also be appended as per requirements. For this purpose, the “+=” shorthand operator can add the values at the end of the array.

For instance, we have an array “arr” having three values. Use the “+=” operator and add the “RHEL” string at the end of it:

$ arr=(Linux Ubuntu Debian)                      #Declare an array
$ arr+=(RHEL)                                    #Append an array

The array append operation has been done without any error.

Execute the “echo” command having “@(ampersand)” to print all the values of the “arr” appended array:

$ echo ${arr[@]}

The “RHEL” has been added at the end of the “arr” array.

Example 6: Update an Indexed Array

The bash index array element can be updated once declared. The updation of an element follows the same method as for an array initialization.

Suppose to update the second index element of the “arr” array, i.e., “Debian.” The array value is specified with the index “[2]” with a new value “Arch”:

$ echo ${arr[@]}                        #Print the array values
$ arr[2]=Arch                           #Update element placed at second index

The “Debian” element has been updated with a new “Arch” element.

Example 7: Length of Indexed Array

To know how many values are present in an array, i.e., length of an array with the help of the “#(hash)” symbol:

$ echo ${#arr[@]}

The output shows the length of an “array” is “4”.

Example 8: Iterate an Indexed Array Through Loop

Looping provides the simplest way to iterate all the array values simultaneously. Let’s see its practical implementation through a “bash.sh” script:

Code:

#!/bin/bash
array=(one two three four five six seven eight nine ten eleven twelve)
for n in ${array[@]}
do
        echo $n
done

In the above code:

  • An “array” initializes 12 strings that will print using the “for” loop.
  • The “for” loop contains a variable “n” that stores the new value of the “array” at each iteration.
  • The do and done statements represent the start and end of the “for” loop that encloses an “echo” statement.
  • The “echo” statement prints each value of the “array” one by one in the terminal:

Save and exit the bash.sh in the text editor.

Execute the “bash.sh” script and check the output:

$ ./bash.sh

The “for” loop has printed all the values of the “array” sequentially in the terminal.

Example 9: Indexed Array Slicing

Array slicing is the concept of accessing the desired subset of elements at a certain index position. Follow the below-stated basic syntax:

Syntax:

$ {my_array[@]:index:len}                      #For Index at specified length
$ {my_array[@]::len}                           #Only for length
$ {my_array[@]:index}                          #Only for index

Let’s implement the syntax in an array:

An “array1” is declared as an example having integer and string values:

$ array1=(one 2 three 4 five 6 seven 8 nine 10 eleven 12)

To get the array element that starts from the “3rd” index and returns the array length “2”, use the “echo” command with the slicing array syntax:

$ echo ${array1[@]:3:2}

The output shows the third index element and displays the 2 elements as per defined length.

Get Elements Start From Specific Index:

To get the array length starting from the desired index element, specify the index separated by “semicolon(:)”:

$ echo ${array1[@]:7}

The output displays the array values starting from “7” index till the end.

Get a Particular Length of Array:

Similar to the index the user can also print the array element starting from zero to the particular length:

$ echo ${array1[@]::7}

The output prints the 7 array elements starting from the “0” index.

Example 10: Remove an Array

To remove an array, use the “unset” command with the array name in the terminal. It removes the declared variable from the “arr” array:

$ unset arr

The “unset” has removed all the values of the “arr” array. For more verification, execute the “echo” command:

$ echo ${arr[@]}

The “echo” command shows an empty array “arr” which confirms that all values of “arr” have been removed.

Example 11: Remove Particular Array Element 

The “unset” command also assists the users in removing the particular element of an “arr” instead of the whole array. As an example, the “my_array” is taken having 4 values:

$ echo ${my_arr[@]}

Specify the desired index value i.e “[2]” for the RHEL alongside the “unset” command in this format:

$ unset my_arr[2]

The output verifies the “RHEL” has been removed from “my_arr” array.

Conclusion

The “Bash Indexed” array is a sequential arrangement of different types of elements associated with an “index”. The index specifies the position of an element in the array and can be used to update and print its value. The array values can be printed using the built-in “echo” command. In addition, it also assists the user in displaying certain values through its special “array slicing” feature.

This guide has provided a detailed view of how bash indexed array works with practical examples.