Index of Element in Array
To find the index of specified element in an array in Bash, use For loop to iterate over the index of this array. In the for loop body, check if the current element is equal to the specified element. If there is a match, we may break the For loop and we have found index of first occurrence of specified element. If we do not use break after finding a match, and continue matching rest of the elements until the end of array, we get the index of last occurrence of element in the array.
Example
In the following examples, we cover the scenarios of finding the first and last occurrences of the specified element in the given array.
Index of First Occurrence of Element in Array
In the following script, we take an array of strings, and find the index of first occurrence of element "mango"
.
For this use case, we use break statement in the For loop. After we found a match with the specified element "mango"
, we set the index
with that iteration’s index i
and break the loop.
Example.sh
arr=("apple" "banana" "mango" "cherry" "mango" "grape")
element="mango"
index=-1
for i in "${!arr[@]}";
do
if [[ "${arr[$i]}" = "${element}" ]];
then
index=$i
break
fi
done
if [ $index -gt -1 ];
then
echo "Index of Element in Array is : $index"
else
echo "Element is not in Array."
fi
Output
Index of Element in Array is : 2
Index of Last Occurrence of Element in Array
In the following script, we take an array of strings, and find the index of last occurrence of element "mango"
.
For this use case, we do not use break statement in the For loop. We repeat the process of matching the given element "mango"
to the elements in the array, till we iterate to the end of array. By the end of For loop execution, index
contains the index of last occurrence of specified element "mango"
.
Example.sh
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 "Index of Element in Array is : $index"
else
echo "Element is not in Array."
fi
Output
Index of Element in Array is : 4
Conclusion
In this Bash Tutorial, we have learnt how to find the index of specified element in an array in Bash shell. We have covered the scenarios of finding the first or last occurrence of specified element in the array, with examples.