Get the index of a value in a Bash array

I have something in bash like

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

And I would like to do something like

echo ${myArray['green']}

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


Solution 1:

This will do it:

#!/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

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

Solution 2:

You must declare your array before use with

declare -A myArray
myArray=([red]=1 [orange]=2 [green]=3)
echo ${myArray['orange']}

Solution 3:

There is also one tricky way:

echo ${myArray[@]/green//} | cut -d/ -f1 | wc -w | tr -d ' '

And you get 2 Here are references

Solution 4:

No. You can only index a simple array with an integer in bash. Associative arrays (introduced in bash 4) can be indexed by strings. They don't, however, provided for the type of reverse lookup you are asking for, without a specially constructed associative array.

$ declare -A myArray
$ myArray=([red]=0 [orange]=1 [green]=2)
$ echo ${myArray[green]}
2

Solution 5:

A little more concise and works in Bash 3.x:

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

for i in "${!my_array[@]}"; do
   [[ "${my_array[$i]}" = "${value}" ]] && break
done

echo $i