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