Bash: How to Get the Index of an Item in Array


Often you may want to get the index of a specific item in an array in Bash.

You can use the following basic syntax to do so:

for i in "${!my_array[@]}"; do
   if [[ "${my_array[$i]}" = "Hawks" ]]; then
      echo "${i}";
   fi
done

This particular example will return the index of the item named “Hawks” in the array named my_array.

Note that if the item appears multiple times in the array then this syntax will return the index number of each occurrence of the item in the array.

If you would only like to return the first occurrence of the item in the array then you could add a break statement as follows:

for i in "${!my_array[@]}"; do
   if [[ "${my_array[$i]}" = "Hawks" ]]; then
      echo "${i}";
      break;
   fi
done

The following example shows how to use this syntax in practice.

Example: Get the Index of an Item in Array in Bash

Suppose that we create the following array in Bash named my_array that contains the names of various basketball teams:

my_array=(Mavs Hawks Mavs Nets Kings Hawks Lakers)

Suppose that we would like to get the index of the item named Hawks within the array.

We can use the following syntax to do so:

for i in "${!my_array[@]}"; do
   if [[ "${my_array[$i]}" = "Hawks" ]]; then
      echo "${i}";
   fi
done

The following screenshot shows how to use this syntax in practice:

Bash get index of item in array

Note that this returns the values 1 and 5, which represent the index values of each item in the array named Hawks.

Note: The index value of the first item in the array is zero.

If we would only like to return the index value of the first occurrence of “Hawks” then we could use the following syntax instead:

for i in "${!my_array[@]}"; do
   if [[ "${my_array[$i]}" = "Hawks" ]]; then
      echo "${i}";
      break;
   fi
done

The following screenshot shows how to use this syntax in practice:

Bash get index of first occurrence of item in array

Notice that this returns the value 1, which represents the index value of the first occurrence of the item in the array named Hawks.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Copy an Array
Bash: How to Find the Intersection of Two Arrays
Bash: How to Get Unique Values from Array

Leave a Reply