Issue
I have a variable value
which is 25. I want to search for that variable in an array with several elements and get the position in my array that matches the value of my variable. In this example, I should get that what I am looking for is position 3 as the 25 matches my variable. When it finds the value I want to store it in a variable so my result
variable should be 3.
value=25
array=( 11 13 17 25 36 )
result=0
My idea is to go through the array with a for loop and if it finds the value it stores it in another variable. This is what I tried:
for i in ${array[@]}; do
if [[ $i -eq $value ]]; then
result=$i
fi
done
But this returns 25 and not its position, how can I return its position in the array?
Solution
You can do something like this:
Assuming your array has only positive integers, declared result=-1
so that it prints -1
if no match is found.
Use a separate variable like index
.
And increment its value by 1
as the loop progresses forward.
value=25
array=( 11 13 17 25 36 )
result=-1
index=0
for i in ${array[@]}; do
if [[ $i -eq $value ]]; then
result=$index
fi
index=$((index+1))
done
echo $result
Answered By - Novice Answer Checked By - Willingham (WPSolving Volunteer)