比如定義數組:
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數組里面的一項時才滿足執行條件,所以很多場景下精確匹配更實用。
