比如定义数组:
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数组里面的一项时才满足执行条件,所以很多场景下精确匹配更实用。