Bash判断变量值是否在数组内的随记

来自WILO & 三线的随记
跳到导航跳到搜索

数组基本操作

[root@router ~]# array=(
> 123
> 456
> 789
> )

[root@router ~]# echo ${array[*]}
123 456 789

[root@router ~]# echo ${array[@]}
123 456 789

[root@router ~]# echo ${#array[@]}
3


判断变量是否在数组内

Method 1

echo "${array[@]}" | grep -wq "$var" &&  echo "Yes" || echo "No"


Method 2

for i in ${array[@]}
do
   [ "$i" == "$var" ] && echo "yes"
done


Method 3

[[ ${array[@]/${var}/} != ${array[@]} ]] && echo "Yes" || echo "No"

Question: diff ?

[[ ${array[@]/${var}} != ${array[@]} ]] && echo "Yes" || echo "No"

What is the principle ??