Get the index of a value in a Bash array

后端 未结 15 775
说谎
说谎 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:22

    I wanted something similar myself and avoiding a loop, came up with ...

    myArray=('red' 'orange' 'green')
    declare -p myArray | sed -n "s,.*\[\([^]]*\)\]=\"green\".*,\1,p"
    

    ... which leaves stdout unsullied should the element not be found...

    $ myArray=('red' 'orange' 'green')
    $ declare -p myArray | sed -n "s,.*\[\([^]]*\)\]=\"green\".*,\1,p"
    2
    
    $ declare -p myArray | sed -n "s,.*\[\([^]]*\)\]=\"gren\".*,\1,p"
    $
    

    After which I googled, found this question and thought I'd share ;)

提交回复
热议问题