How can I check if a string is in an array without iterating over the elements?

后端 未结 9 2327
眼角桃花
眼角桃花 2021-02-13 18:54

Is there a way of checking if a string exists in an array of strings - without iterating through the array?

For example, given the script below, how I can correctly impl

9条回答
  •  南旧
    南旧 (楼主)
    2021-02-13 19:20

    You can use an associative array since you're using Bash 4.

    declare -A array=([hello]= [world]= [my]= [name]= [is]= [perseus]=)
    
    test='henry'
    if [[ ${array[$test]-X} == ${array[$test]} ]]
    then
        do something
    else
        something else
    fi
    

    The parameter expansion substitutes an "X" if the array element is unset (but doesn't if it's null). By doing that and checking to see if the result is different from the original value, we can tell if the key exists regardless of its value.

提交回复
热议问题