Get the index of a value in a Bash array

后端 未结 15 809
说谎
说谎 2021-01-30 03:41

I have something in bash like

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

And I would like to do something like

echo ${         


        
15条回答
  •  清歌不尽
    2021-01-30 04:32

    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

提交回复
热议问题