简单描述:
如数组。期望编写函数
,分别接受两个参数
和
,返回——0(True)或1(False)
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数组-判断某个元素是否在数组内的几种方法