bash shell 获取数组中给定元素的下标

 
#获取数组中给定元素的下标
#参数:1 数组; 2 元素
#返回: 元素在数组中的下标,从 0 开始;-1 表示未找到
# 例子:
#    获取数组 xrsh_array 中元素 i3 的下标
#    xrsh_array=(i1,i2,i3)
#    xrsh_tmp=`echo ${xrsh_array[*]}`
#     xrsh_arritemidx "$xrsh_tmp" "i3"
#    返回 2
# 注意:数组作为参数使用时需要先转换
function xrsh_arritemidx()
{
   local _xrsh_tmp
   local _xrsh_cnt = 0
   local _xrsh_array = ` echo "$1" `
   for _xrsh_tmp in ${_xrsh_array[ *]}; do
     if test "$2" = "$_xrsh_tmp"; then
       echo $_xrsh_cnt
       return
     fi
    _xrsh_cnt =$(( $_xrsh_cnt + 1 ))
   done
   echo "-1"
}

你可能感兴趣的:(shell,bash,shell,function)