我如何检查数组是否包含bash中特定值以外的其他内容?

问题描述:

arr=( d d d a)

下面的代码应该检查它是否包含 d .有没有类似的方法来检查它是否包含除 d 之外的其他内容?

The code below is supposed to check if it contains d. Is there a similar way to check if it contains anything else than d?

if [[ " ${arr[*]} " == *" d "* ]]; then                                         
 echo "arr contains d"  
fi

只要您不在Array元素中使用空格,就可以使用:

As long as you're not using space in Array elements you can use:

[[ " ${arr[*]} " == *" "[^d]" "* ]] && echo "array has non-d element" || echo "no"

测试:

arr=(d d d a)
[[ " ${arr[*]} " == *" "[^d]" "* ]] && echo "array has non-d element" || echo "no"
array has non-d element

arr=(d d d)
[[ " ${arr[*]} " == *" "[^d]" "* ]] && echo "array has non-d element" || echo "no"
no