• Bash数组-判断某个元素是否在数组内的几种方法


    声明一个数组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 ~]#
    
  • 相关阅读:
    客户细分那点事_实践1
    和各种人去交流_好玩的事
    客户细分那点事_理论篇
    模型持久化
    天赋是积累出来的——转载自周鸿祎博客
    Pytorch——torch.nn.Sequential()详解
    第2章 Python序列
    Pytorch将数据打包
    线性回归的从零开始实现
    plt.scatter 各参数详解
  • 原文地址:https://www.cnblogs.com/thatsit/p/bash-shu-zupan-duan-mou-ge-yuan-su-shi-fou-zai-shu.html
Copyright © 2020-2023  润新知