Check if a Bash array contains a value

前端 未结 30 2953
执笔经年
执笔经年 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:03

    If you want to do a quick and dirty test to see if it's worth iterating over the whole array to get a precise match, Bash can treat arrays like scalars. Test for a match in the scalar, if none then skipping the loop saves time. Obviously you can get false positives.

    array=(word "two words" words)
    if [[ ${array[@]} =~ words ]]
    then
        echo "Checking"
        for element in "${array[@]}"
        do
            if [[ $element == "words" ]]
            then
                echo "Match"
            fi
        done
    fi
    

    This will output "Checking" and "Match". With array=(word "two words" something) it will only output "Checking". With array=(word "two widgets" something) there will be no output.

提交回复
热议问题