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

来自三线的随记
Admin讨论 | 贡献2020年4月16日 (四) 12:47的版本

数组基本操作

[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 ??