Index Array in Bash [Explained]

An indexed array is a data structure that stores a collection of elements accessed by numerical indices. These arrays are numerically indexed starting from zero by default. But it can be assigned values to specific indices, iterate over them, or perform various operations like adding or removing elements.

Let’s walk through the essential concepts along with Bash script examples to work with the Bash index array.

What is an Indexed Array in Bash?

An indexed array is a type of array that stores values (elements) and assigns an integer number as an index starting from 0 to N. Unlike some programming languages, Bash indexed array holds values of different data types (string, integer, etc).bash index arrayThe indexed array in Bash has no upper limit on its size since it can store an indefinite number of elements depending on memory availability.

NOTE: To learn more about arrays in Bash, read the article “Bash Array”

Create an Indexed Array

The foremost step towards working with an Indexed array is to create it. Creation of an indexed array typically comprises naming the array, using parenthesis, and placing the values inside the parenthesis. To create an indexed array in Bash use the syntax: array_name=(value1 value2 value3…. valueN).

Look at the example below to create an indexed array in Bash:

#!/bin/bash

#Array creation
black=(tony jahan rubayet)

#echo to confirm array creation
echo "indexed array black is created with 3 elements"
EXPLANATION

In the above code, black=(tony jahan rubayet) creates an indexed array black with 3 elements. The echo command in the last line prints a message to confirm the execution of the code to create the bash index array.

bash index array black is created The above script prints the message to confirm the newly created indexed array.

Using the “declare” Command

the declare command is used to declare variables and set their attributes. It’s particularly useful for explicitly defining variables and their behavior within a Bash script. To create an indexed array with the declare command, use the flag -a followed by the array name: declare -a <array_name>.

Here is an example script that shows how to use declare -a to create an indexed array:

#!/bin/bash

#Array creation using declare -a command
declare -a arr1=(1 2 three 4)

#echo to confirm array creation
echo "indexed array arr1 is created with 3 elements"
EXPLANATION

In the script, the declare -a command creates an array arr1 with explicit declaration and the echo command confirms the creation printing a message on the screen.

bash index array created with declare -a command In the above image, you see that the declare -a command has created an indexed array, and echoing the message indexed array arr1 is created with declare -a confirms it.

NOTE: you can create an empty indexed array using declare -a array_name or array_name=() command and assign values later.

View the Length of an Indexed Array

The length expression ${#array[@]} syntax returns the length (total number of elements) of an index array and to print the length of an indexed array, use the syntax: echo ${#array[@]}

Here’s how to print the length of an indexed array in Bash using the syntax echo ${#array[@]}:

#!/bin/bash

#array declaration
keepers=(gilly buzz mushy)

#printing the array
echo ${keepers[*]}

#print the length
echo "the length: ${#keepers[*]}"
EXPLANATION

In the bash script above, the syntax  ${#keepers[*]} returns the length of the array (which is 3)  keepers, and the echo command displays on the screen.

print bash index array lengthIn the image above, you spot that the command echo ${#keepers[*]} prints the length (3) of the array named keepers.

Print an Indexed Array

The length expressions ${array[@]} or ${array[*]} prints all the elements located at specified indices using the echo command.

Here’s how to print an indexed array called artcell in Bash employing the syntax echo ${artcell[@]} and echo ${artcell[*]}:

#!/bin/bash

#Array creation
artcell=(lincoin ershad sazu sezan)

#printing array length to the terminal using both expressions
echo "the array elements printed using \${artcell[@]}: ${artcell[@]}"
echo               # for adding extra spaces between the outputs
echo "the array elements printed using \${artcell[*]}: ${artcell[*]}"
EXPLANATION

In the above code, the expressions ${artcell[@]} and ${artcell[*]} take the array items and print them to the screen using the echo command.

print a bash index arrayPrinting an indexed array named artcell using echo ${artcell[@]} and echo ${artcell[*]}

Note: Though the expressions ${array[@]} and ${array[*]} print all the array elements, there’s a subtle difference between them. The first one expands each element as a separate word while the latter one treats all the elements as a single string to print on the screen.

Using the “printf” Command

The printf command formats and prints text or variables to the standard output. However, to print, the elements of an array in Bash, use the syntax: printf "%s\n" "${array[@]}".

Here is an example of how to use the above syntax printf "%s\n" "${array[@]}" in a Bash script:

#!/bin/bash

#create an array with 3 elements
fruits=("apple" "orange" "banana")

#print the array using printf command
printf "%s\n" "${fruits[@]}"
EXPLANATION

In the above code, the printf command prints the items of the array named fruits using the expression ${fruits[@]}. The \n is a newline character telling printf to display elements with newlines and %s accepts the elements as an argument.

print bash index array using printf commandIn the above-captured image, you see that the printf command prints the array elements with new lines.

Print Specific Elements of an Indexed Array

To print access only the specific elements of an indexed array in Bash, use the index notation syntax echo ${array[index]}.

Here’s an example to access indexed array elements using echo ${array[index]}:

#!/bin/bash

#array declaration
finders=(sherlock byomkesh masud)

#printing the array
echo "all items: ${finders[@]}"

echo

#printing only the 1st element using finders[0]
echo "1st item: ${finders[0]}"
EXPLANATION

In this script, the command echo ${finders[0]} prints the 1st element of the array (sherlock) finders consisting of 3 elements (sherlock byomkesh masud). The previous line prints the entire array using echo ${finders[@]} to display the differences and verify the process.

access elements of a bash index arrayThe above snap states that the expression ${finders[0]} with the echo command prints the 1st element of the finders array which has 3 elements in total.

Print Elements of an Index Array Using the “for” Loop

The for loop in Bash prints the entire indexed array with a new line. It’s a powerful tool that iteratively accesses each array element and prints them with the echo or the printf command

To print an indexed array in Bash using for loops, see the following script:

#!/bin/bash

#Declaring an indexed array and assigning it with values 
drinko=(lichie pine orange)

#looping through the elements to print 
for flavor in ${drinko[@]}
    do
        echo $flavor
done 
EXPLANATION

First, the complete looping expression for elements in ${drinko[@]} iterates through the drinko array until it covers the entire array length (which is 3) and prints the items into the terminal iteratively on new lines using echo $flavor.

printing bash index array using for loopTerminal output to print an indexed array in Bash using the for loop with the echo command

However, loop can print elements from a specific portion of the array. To access array elements from indices S to E exclusive using the loop syntax for ((i = S; i < E; i++)): Again, to access the last N elements from an array, use the syntax for ((i=length-N; i < length; i++)):

Here is a script  to access the last 2 elements of an array:

#!/bin/bash

#array declaration with elements
greenDay=("21Guns" "holiday" "enemy" "basketCase" "forgotten")

# Get the length of the array
length=${#greenDay[@]}

#print the entire array
echo "entire array: ${greenDay[@]}"
echo
echo "last 2:"

# Print the last 2 elements using a for loop
for ((i = length - 2; i < length; i++)); do
    echo "${greenDay[i]}"
done
EXPLANATION

The above script creates an indexed array greenDay with 5 elements. The loop for ((i = length - 2; i < length; i++)) prints the last 2 elements of that array starting from the condition, “i = length – 2” (which is the second-to-last element up to the end of the array), using the command echo ${greenDay[i]}.

printing last 2 elements of an indexed array in BashScript output to access the last 2 elements of the array greenDay using for loop

Printing the Indices of an Indexed Array

To print the index values of the array elements, use the usual length expression ${array[@]} with “!” like this syntax as a prefix along with the echo command like this syntax: echo ${!array[@]}. The exclamation mark (!), in the expression ${!array[@]}, tells the expression to expand the indices of the array rather than the individual elements. Here’s an example:

#!/bin/bash

#array declaration
coach=(donald rhodes whatmore)

#print elements
echo "elements are: ${coach[@]}"

echo

#print the index
echo "the indices are: ${!coach[@]}"
EXPLANATION

In the bash script above, the length expression ${!coach[@]} expands to all the indices of the array coach and the echo command displays the index values 0 1 2 on the screen.

The output will look like this:printing the indices of an indexed array The above script outputs the index values (0 1 2) of the array coach with 3 elements (donald rhodes whatmore).

Appending Elements to an Index Array

To append means to add a new element at the end of an array. The += operator appends a new element to the end of that array with the syntax array+=(element to append).

Here’s an example script to append elements to an indexed array using array+=(element to append):

#!/bin/bash

#array declaration with elements 
example_array=(EEE CE)

#print array before append
echo "before: ${example_array[@]}"

#append element
example_array+=(ME)

#print array after append
echo "after appending: ${example_array[@]}"

EXPLANATION
This script uses the syntax example_array+=(ME) to append a new element ME to the example_array with 2 elements. The final echo command prints the array with 3 elements (EEE CE ME).

append elements to an indexed arrayThe above image shows that the example_array+=(ME) expression adds a new element ME to the array which is evident after printing the array in the last line.

NOTE: To append an array, arr1, to another array, arr2, use arr2+=(${arr1[@]})

Updating Elements of an Indexed Array

To update the content of an array element, assign a new value by using its index value using the syntax: array[index]= new value to assign. Here’s an example:

#!/bin/bash  
#Declaring the array  
declare -a example_array=("welcome" "to" "linuxsimply")  
#Printing all the elements of the Array  
echo "before updation:${example_array[@]}"

#Updating the Array Element  
example_array[2]=softeko  
  
#Printing all the elements of the Array  
echo "after updation:${example_array[@]}"
EXPLANATION

Here, the example_array[2]=softeko expression updates the content of index 2 (3rd position) from linuxsimply to softeko. The echo “after updation:${example_array[@]}” command prints the array with the updated contents.

update indexed array element in BashThe above screenshot states that the command example_array[2]=softeko replaces the item linuxsimply at index 2 of the example_array with softeko.

Slicing an Indexed Array

To slice an indexed array in Bash from a specific starting index to an ending index, use the syntax: ${array_name[@ or *]:Start:Count}.

The slicing expression ${array_name[@ or *]:Start:Count} slices an indexed array beginning from the index Start (0,1,2…) and extracts the number of elements specified by Count. For example, the command echo ${array_name[@ or *]:2:5} prints 5 elements starting from index 2.

To print 5 elements from an array of 8 elements starting from index 2, you can use echo ${array_name[@ or *]:2:5}. Here’s an example:

#!/bin/bash

#create an indexed array
juice=("apple" "banana" "cherry" "date" "grape" "peach" "dragon" "kiwi")

#print entire array
echo ${juice[@]}

#print 5 elements starting from index 2
echo ${juice[@]:2:5}
EXPLANATION

Here, the expression  ${juice[@]:2:5} begins from index 2 to access 5 elements inclusive. Finally, the echo command prints the items to the prompt.

slicing an indexed array in BashThe above snapshot states that the echo ${juice[@]:2:5} command prints 5 elements (cherry date grape peach dragon) out of 8 elements starting from the 3rd element.

Removing Elements of an Indexed Array

To delete an array element, use the unset command followed by the index value like the syntactical format: unset example_array[index]

Here’s an example to show how to remove an element from an indexed array using the unset array_name[index]:

#!/bin/bash

# the array 
brands=(adidas puma nike)

#print array
echo "before removal: ${brands[@]}"

# Deleting nike from the array
unset brands[2]

#printing the array after removal of the element nike 
echo "after removal: ${brands[@]}"
EXPLANATION

In the script, the unset command followed by the syntax (brands[2]) removes the third element nike. After that, the echo command prints the array and shows that the unset command has removed the array element.

remove bash index array elementsThe above image states that the command unset brands[2] has removed the item nike from the brands array.

Remove All the Elements Using ‘()’

To keep an indexed array empty by removing all the items, simply recreate the array using the syntax: array_name=():

#!/bin/bash

# create an array with elements
num=(1 2 3)

#print the array
echo "the current array: ${num[@]}"
echo

#recreate the array 
num=()

#print the array after recreation
echo "elements after recreating: ${num[@]}"
EXPLANATION

Here, the expression num=() recreates the already extant array called num with 3 elements 1 2 3. In turn, it also removes all the items and only the empty array remains which is evident in the last line where the echo command tries to print the elements and gets nothing.

empty an indexed array and remove elementsThe script output to empty an indexed array num using the array creation command num=()

Delete All the Elements Using ‘unset’ Command

The unset command in Bash is used to remove variables and functions. So, it can be used to delete an entire indexed array. It requires only the use of the syntax: unset <array name>.

The below script shows an example of how to use unset to delete all the elements of an indexed array:

#!/bin/bash

# create an array
bat=(man teen child)

#print array before deletion
echo "before deletion:${bat[@]}" 

#delete the array with unset
unset bat

#print array again
echo "after deletion:${bat[@]}"
EXPLANATION

In, the above script the line unset bat deletes the array named bat. Printing the array after running the unset bat displays no elements on the screen that verify array element removal.

delete array elements using the unset commandIn the image, you see there is no output to print any content using echo ${bat[@]}. This empty result is the exemplar that the array bat is not extant anymore.

Find the Index of a Specific Element

To find the index of a specific element of an indexed array, use the Bash for loop to iterate over the array and match the condition if the current element equals the specified element. If yes, the loop stores the index value and breaks to find the value of the first occurrence. Otherwise, the loop covers the entire array and tracks the index of the last occurrence of that element.

Find First Occurrence

To find the index of the first occurrence of the specified item using the for loop, see the script below:

#!/bin/bash

#create array
arr=("banana" "mango" "cherry" "mango" "grape")
#Specified element 
element="mango"
index=-1  # initializing the flag to -1
 
#loop to track element
for i in "${!arr[@]}";
do
    if [[ "${arr[$i]}" = "${element}" ]];
    then
        index=$i
        break
    fi
done

#printing the index if found 
if [ $index -gt -1 ];
then
    echo "first occurence of $element in Array is at index : $index"
else
    echo "Element is not in Array."
fi
EXPLANATION

The above script finds the 1st occurred index of the element “mango”. Here, the for i in "${!arr[@]} loop with break statement finds the match for “mango” and after finding the element, it sets the value of the index variable to the current value of i and immediately breaks the loop.

find first index of an index array elementThe above image states that the for loop returns the index of the element “mango” as 1 which is the position of its 1st occurrence.

Find Last Occurrence

To find the index of the last occurrence of the specified element, use the same condition but without the break statement:

#!/bin/bash

arr=("apple" "banana" "mango" "cherry" "mango" "grape")

element="mango"
index=-1
 
for i in "${!arr[@]}";
do
    if [[ "${arr[$i]}" = "${element}" ]];
    then
        index=$i
    fi
done

if [ $index -gt -1 ];
then
    echo "Last occurence of $element in Array is at index : $index"
else
    echo "Element is not in Array."
fi

find last index of an index array elementScript output to print the last occurrence index value of the specified element “mango”

Reordering an Index Array

Reordering an array typically refers to rearranging the elements within the array according to a specific order or criteria. This can involve sorting the elements based on numerical or alphabetical order, shuffling them randomly, or arranging them in a custom-defined sequence.

Here’s an example script for reordering an indexed array in Bash:

#!/bin/bash
items=("Mango" "Pineapple" "Strawberry" "Cherry" "Grapes")
order=(4 2 0 3 1)
#print array
echo ${items[@]}
echo

#print elements in reorder
for i in "${order[@]}"
do
   echo ${items[$i]}
done
EXPLANATION

In the above example, the order array holds the new order of elements (4 2 0 3 1). Then, the for loop for i in "${order[@]}" iterates the order array to use each value as an index and uses this index to print the array items in a reordered pattern.

reordering a Bash index arrayIn the snap above, you see the original pattern of the items array and then the reordered pattern to display items using another indexed array order.

Conclusion

Indexed arrays in Bash are versatile and commonly used for storing and manipulating collections of items, offering flexibility in managing data within scripts. Hope this article guides you through the ins and outs of the indexed array in Bash with practical examples. Hope it elevates your data-handling capability for efficient script development. Still, if you face any difficulty, feel free to share in the comment section. Happy scripting!

Frequently Asked Questions

What is the difference between array length and array size in Bash?

Array length refers to the number of elements present in the array in Bash. You can get the array length by using echo ${#array[@]} command. Contrarily, the array size is the allotted or occupied memory by the array. In Bash, arrays automatically resize so there’s no pre-defined size in Bash array.

How to echo a Bash Array?

To echo a Bash array, use the length expression command echo ${array[@]}. For example, to echo an array nums, the command is: echo ${nums[@]}. You can also use length expression ${nums[*]} prefixing with the echo command.

Can I print the index value of an array in Bash?

Yes, you can use the syntax echo ${!array_name[@]} to print the indices of an indexed array in Bash. For instance, to print the indices of the nums array with 3 elements use: echo ${!nums[@]}. The output will be 0 1 2.

How to delete an indexed array in Bash?

Use the unset command followed by the array name to delete that array. For instance, the unset example_array will delete the array called example_array.

How can I access the last element of an Indexed array?

You can use negative indexing  -1 with the echo command to access the last element of an indexed Bash array.  For example, the command echo ${items[-1]} will print the last element of the items array.

Can I use the “printf” command in the for loop to print an indexed array?

Yes, you can use the printf command within the for loop to print an indexed array like the following:

myArray=("element1" "element2" "element3")

for element in "${myArray[@]}"; do
    printf "%s " "$element"
done

How to print the length of an indexed array in Bash?

The length of an indexed array means the number of elements stored in the array. To print the length of an indexed array, use the command echo ${#array[@]}

Related Articles


<< Go Back to Bash Array | Bash Scripting Tutorial

5/5 - (1 vote)
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
Md Masrur Ul Alam

Assalamu Alaikum, I’m Md Masrur Ul Alam, currently working as a Linux OS Content Developer Executive at SOFTEKO. I completed my Bachelor's degree in Electronics and Communication Engineering (ECE)from Khulna University of Engineering & Technology (KUET). With an inquisitive mind, I have always had a keen eye for Science and Technolgy based research and education. I strongly hope this entity leverages the success of my effort in developing engaging yet seasoned content on Linux and contributing to the wealth of technical knowledge. Read Full Bio

Leave a Comment