Check if a Bash array contains a value

前端 未结 30 2413
执笔经年
执笔经年 2020-11-22 07:14

In Bash, what is the simplest way to test if an array contains a certain value?

30条回答
  •  抹茶落季
    2020-11-22 07:51

    Using parameter expansion:

    ${parameter:+word} If parameter is null or unset, nothing is substituted, otherwise the expansion of word is substituted.

    declare -A myarray
    myarray[hello]="world"
    
    for i in hello goodbye 123
    do
      if [ ${myarray[$i]:+_} ]
      then
        echo ${!myarray[$i]} ${myarray[$i]} 
      else
        printf "there is no %s\n" $i
      fi
    done
    

提交回复
热议问题