arraysbashindexing

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

  • 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