arr=( d d d a)
下面的代码应该检查它是否包含d
。是否有类似的方法来检查它是否包含除d
以外的任何内容?
if [[ " ${arr[*]} " == *" d "* ]]; then
echo "arr contains d"
fi
答案 0 :(得分:2)
您可以遍历数组并检查每个元素。可能有一个比下面更好的方法,但这个方法应该有效:
# Loop over the array elements
for i in "${arr[@]}";
do
# Check if it is not d
if [[ "$i" != "d" ]]; then
echo "array element is not d. it is $i";
fi
done
答案 1 :(得分:0)
只要你没有在数组元素中使用空格,你就可以使用:
[[ " ${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