如何在bash中检查数组是否包含除特定值以外的任何内容?

时间:2015-09-30 18:07:52

标签: arrays bash

arr=( d d d a)

下面的代码应该检查它是否包含d。是否有类似的方法来检查它是否包含除d以外的任何内容?

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

2 个答案:

答案 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