如何使用bash函数获取数组中元素的索引

艾哈迈德 :

这是我的代码:

function get_index() {
 my_array="$1"
 value="$2"
 for i in "${!my_array[@]}"; do
   if [[ "${my_array[$i]}" = "${value}" ]]; then
       echo "was found"
       echo "${i}";
   fi
 done
 return -1
}

echo "index test"
get_index "${cut_pages[@]}" 5
index=$?
echo $index

数组包含2并且5必须返回1,但返回255

有什么问题?

弗雷迪:

您可以使用对数组的名称引用,而不是将整个数组作为单独的参数传递:

function get_index() {
  local -n my_array=$1 # use -n for a reference to the array
  for i in "${!my_array[@]}"; do
    if [[ ${my_array[i]} = $2 ]]; then
      printf '%s\n' "$i"
      return
    fi
  done
  return 1
}

cut_pages=( 1 2 3 4 5 )
index=$(get_index cut_pages 5) && echo "index=$index"

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章