【问题标题】:Is there a way to search sameness in an array with bash without loop?有没有办法在没有循环的情况下使用 bash 在数组中搜索相同性?
【发布时间】:2017-08-11 07:46:35
【问题描述】:

所以我有一个带有字符串的数组,以及另一个字符串变量本身,我想做一个过程,当变量是数组的元素之一时。是否可以写一个 IF 行,而不用循环检查所有元素?

【问题讨论】:

    标签: bash loops if-statement


    【解决方案1】:

    Bash 现在支持关联数组,即键为字符串的数组:

    declare -A my_associative_array
    

    因此,您可以将您的经典数组转换为关联数组,并通过简单的方式访问您正在寻找的条目:

    my_string="foo bar"
    my_associative_array["$my_string"]="baz cux"
    echo "${my_associative_array[$my_string]}"
    echo "${my_associative_array[foo bar]}"
    

    并测试密钥的存在:

    if [ "${my_associative_array[$my_string]:+1}" ]; then
      echo yes;
    else
      echo no;
    fi
    

    来自 bash 手册:

       ${parameter:+word}
              Use Alternate Value.  If parameter is null or unset, nothing
              is substituted, otherwise the expansion of word is substituted.
    

    因此,如果键 $my_string 为 null 或未设置,${my_associative_array[$my_string]:+1} 扩展为空,否则扩展为 1。其余的只是if bash 语句结合test ([]) 的经典用法:

    if [ 1 ]; then echo true; else echo false; fi
    

    打印true while:

    if [ ]; then echo true; else echo false; fi
    

    打印false。如果您更愿意将空条目视为任何其他现有条目,只需省略冒号:

    if [ "${my_associative_array[$my_string]+1}" ]; then
      echo yes;
    else
      echo no;
    fi
    

    来自 bash 手册:

              Omitting the colon results in a test only for a parameter
              that is unset.
    

    【讨论】:

    • 请你也写一个检查的例子好吗?
    猜你喜欢
    • 2016-05-12
    • 1970-01-01
    • 2018-07-29
    • 2013-09-03
    • 2019-01-18
    • 2020-12-20
    • 2021-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多