shell判断参数值是否在数组内的方法


比如定义数组:

arr=("one" "tow" "thr" "three" "four")

 1. 模糊匹配,也可以理解为子集匹配

if [[ "${arr[*]}" =~ ${var} ]]; then
# do something
fi

 优点是比较简洁,缺点是匹配不精确。比如参数为:th, thr, thre, three 均满足执行条件。

 

2. 精确匹配,需要函数实现:

unction contains() {
    local n=$#
    local value=${!n}
    for ((i=1;i < $#;i++)) {
        if [ "${!i}" == "${value}" ]; then
            echo "y"
            return 0
        fi
    }
    echo "n"
    return 1
}
 
A=("one" "two" "three four")
if [ $(contains "${arr[@]}" "thre") == "y" ]; then
    echo "contains thre"
fi
if [ $(contains "${arr[@]}" "three") == "y" ]; then
    echo "contains three"
fi

 必须完整匹配arr数组里面的一项时才满足执行条件,所以很多场景下精确匹配更实用。

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM