Bash配列-ある要素が配列内にあるかどうかを判断するいくつかの方法
1684 ワード
配列arrayを宣言し、テスト対象要素varを宣言します。
array=(
element1
element2
element3
)
var="element1"
次にvarがarrayの要素であるかどうかをいくつかの方法でそれぞれテストします。
判断方法1:
echo "${array[@]}" | grep -wq "$var" && echo "Yes" || echo "No"
判断方法2:
for i in ${array[@]}
do
[ "$i" == "$var" ] && echo "yes"
done
判断方法3:これは個人感覚の最も巧みなテスト方法であり,bash配列の内蔵方法を用いた.
[[ ${array[@]/${var}/} != ${array[@]} ]] && echo "Yes" || echo "No"
デモのテスト
# array、 var
[root(0)@thatsit ~]# array=(
> element1
> element2
> element3
> )
[root(0)@thatsit ~]#
[root(0)@thatsit ~]# var="element1"
#
[root(0)@thatsit ~]# echo ${array[@]}
element1 element2 element3
[root(0)@thatsit ~]# echo $var
element1
[root(0)@thatsit ~]#
# 1
[root(0)@thatsit ~]# echo "${array[@]}" | grep -wq "$var" && echo "Yes" || echo "No"
Yes
[root(0)@thatsit ~]#
# 2
[root(0)@thatsit ~]# for i in ${array[@]}
> do
> [ "$i" == "$var" ] && echo "yes"
> done
yes
[root(0)@thatsit ~]#
# 3
[root(0)@thatsit ~]# [[ ${array[@]/${var}/} != ${array[@]} ]] && echo "Yes" || echo "No"
Yes
[root(0)@thatsit ~]#
転載先:https://www.cnblogs.com/thatsit/p/bash-shu-zupan-duan-mou-ge-yuan-su-shi-fou-zai-shu.html