How to check index of a array element in shell script?

Example - Script to find the index of a month from array

MONTHS="Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec"
set -A MON $MONTHS
A="Sun May 23 09:34:30 GMT 2010"
getMonth=`echo $A|cut -c5-7`  ##getMonth=May
Arrayindex_in_MONTHS_array= ????        # { 0,1,2,3,4 } - at fifth place

Output should come 4 => $Arrayindex_in_MONTHS_array

Thanks,
kuldeep

In Bash:

#!/bin/bash

getIndex() {
	index=0
	while [ "${ARRAY[$index]}" != "$VALUE" ] && [ $index -lt "${#ARRAY[@]}" ]; do ((index++)); done
	if [ $index -lt "${#ARRAY[@]}" ]; then
		echo $index
	else
		echo 'Not Found'
	fi
}

ARRAY=(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)
VALUE='May'

getIndex

exit 0

In Bash (simpler?):

#!/bin/bash

getIndex() {
	for ((index=0; index<${#ARRAY[@]}; index++)); do 
		if [ "${ARRAY[$index]}" = "$VALUE" ]; then
			echo $index
			return
		fi
	done
	echo 'Not Found'
}

ARRAY=(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)
VALUE='May'

getIndex

exit 0

A third version, just a modified 2nd version:

#!/bin/bash

getIndex() {
	index=0; while ((index<${#ARRAY[*]})); do
		if [ "${ARRAY[$index]}" = "$VALUE" ]; then
			echo $index; return
		fi
	((index++)); done
	echo 'Not Found'; return 1
}

ARRAY=(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)
VALUE='May'

getIndex

exit 0

Another way to get the index (month number):

MONTHS="JanFebMarAprMayJunJulAugSepOctNovDec"
A="Sun May 23 09:34:30 GMT 2010"

MonthNumber=`echo $A | awk '{printf("%d\n", (index("JanFebMarAprMayJunJulAugSepOctNovDec",$2)+2)/3)}'`
#!/bin/bash
MONTHS="Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec"
A="Sun <May 23 09:34:30 GMT 2010"
getMonth=`echo $A|cut -c5-7`  ##getMonth=May
SUB=${MONTHS%$getMonth*}
index_in_MONTHS=$((${#SUB}/4+1))       # { 0,1,2,3,4 } - at fifth place
echo index_in_MONTHS

Hey Thanks All,
All post are really great.
It is working now.

---------- Post updated at 08:24 PM ---------- Previous update was at 01:45 PM ----------

any function to count the array element available in array ?
like in my script the MONTHS array has 12 element. i just want to store in in a variable so that i can run the loop accordingly.

Thanks

echo ${#MON[*]}
IndexOf()    {
    local i=1 S=$1; shift
    while [ $S != $1 ]
    do    ((i++)); shift
        [ -z "$1" ] && { i=0; break; }
    done
    echo $i
}
# usage example
ARRAY=(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)
VALUE='May'
IndexOf $VALUE ${ARRAY[@]}
# will echo 0 if not found

Thanks all it worked.