Check if a Bash array contains a value

前端 未结 30 2943
执笔经年
执笔经年 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 08:02

    I had the case that I had to check if an ID was contained in a list of IDs generated by another script / command. For me worked the following:

    # the ID I was looking for
    ID=1
    
    # somehow generated list of IDs
    LIST=$(  )
    # list is curiously concatenated with a single space character
    LIST=" $LIST "
    
    # grep for exact match, boundaries are marked as space
    # would therefore not reliably work for values containing a space
    # return the count with "-c"
    ISIN=$(echo $LIST | grep -F " $ID " -c)
    
    # do your check (e. g. 0 for nothing found, everything greater than 0 means found)
    if [ ISIN -eq 0 ]; then
        echo "not found"
    fi
    # etc.
    

    You could also shorten / compact it like this:

    if [ $(echo " $( 
    
                                     
                  
提交回复
热议问题