获取Bash数组中值的索引 [英] Get the index of a value in a Bash array

查看:531
本文介绍了获取Bash数组中值的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在bash中有一些东西,例如

I have something in bash like

myArray=('red' 'orange' 'green')

我想做类似的事情

echo ${myArray['green']}

在这种情况下将输出2.这可以实现吗?

Which in this case would output 2. Is this achievable?

推荐答案

这可以做到:

#!/bin/bash

my_array=(red orange green)
value='green'

for i in "${!my_array[@]}"; do
   if [[ "${my_array[$i]}" = "${value}" ]]; then
       echo "${i}";
   fi
done

很明显,如果将其转换为函数(例如get_index()),则可以使其通用化

Obviously, if you turn this into a function (e.g. get_index() ) - you can make it generic

这篇关于获取Bash数组中值的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆