shell编程:判断数组是否包含某个元素

简单描述:
如数组$arr=(1\ 2\ 3\ 4), target_1=4, target_2=5$。期望编写函数$IsContains()$,分别接受两个参数$arr$和$targe_i$,返回——0(True)或1(False)

1
2
3
4
5
6
7
8
9
10
11
12
13
IsContains(){
# 把原来的arr新赋值给一个新数组
narr=($1)
# 逻辑是判断删除\$2后的数组是否与原数组相同,不同则标明包含元素,相同(没有\$2可删除)则标明不包含元素
[[ ${narr[@]/$2/} != ${narr[@]} ]];echo $?
}
arr=(1 2 3 4)
target1=4
target2=5
# ${arr[*]}!, not ${arr[@]}! TestResult: ${arr[@]}=> narr=(1), ${arr[*]=> narr=(1 2 3 4)
# but i don't know why
echo `IsContains "${arr[*]}" $target1`
echo `IsContains "${arr[*]}" $target2`

代码中有个疑问,当调用的主参使用$arr[@]时,IsContains函数中$1=(1),当调用的主参使用$arr[*]时,IsContains函数中$1=(1 2 3 4)。不知道为什么,可能我对shell编程还是一知半解吧。望能看到这篇博客的大佬给予解答,谢谢。

另外关于shell判断逻辑——if [[]]、(())、[] 的区别,可以参考博客:[shell if [[ ]]和 ]区别 || &&
该文章有参考博客:Bash数组-判断某个元素是否在数组内的几种方法

Shell数组与字符串:shell脚本编程进阶之数组、字符串切片