Get the index of a value in a Bash array

后端 未结 15 516
说谎
说谎 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条回答
  •  闹比i
    闹比i (楼主)
    2021-01-30 04:41

    This outputs the 0-based array index of the query (here "orange").

    echo $(( $(printf "%s\n" "${myArray[@]}" | sed -n '/^orange$/{=;q}') - 1 ))
    

    If the query does not occur in the array then the above outputs -1.

    If the query occurs multiple times in the array then the above outputs the index of the query's first occurrence.

    Since this solution invokes sed, I doubt that it can compete with some of the pure bash solutions in this thread in efficiency.

提交回复
热议问题