【问题标题】:How to distinguish between null and empty string when retrieving from a bash map从 bash 映射中检索时如何区分空字符串和空字符串
【发布时间】:2012-09-26 10:18:37
【问题描述】:

我无法找出如何在 bash 映射中检查 null(或未设置?)。 也就是说,我想将我可以放置在地图中的空字符串与我在地图中根本没有放置任何东西(对于那个特定的键)的情况不同。

比如看代码:

#!/bin/bash

declare -A UsersRestrictions
UsersRestrictions['root']=""


if [[ -z "${UsersRestrictions['root']}" ]] ; then
    echo root null
else 
    echo root not null
fi

if [[ -z "${UsersRestrictions['notset']}" ]]; then
    echo notset null
else 
    echo notset not null
fi

我希望“root”的测试给我'not null',而“notset”的测试给我'null'。但我在这两种情况下都得到了相同的结果。我已经搜索了其他可能的方法,但到目前为止都给了我相同的结果。有没有办法做到这一点?

谢谢!

【问题讨论】:

    标签: bash testing map null string


    【解决方案1】:

    使用-z ${parameter:+word} 作为您的测试条件。如果参数为 null 或未设置,则始终为 true,否则为 false。

    来自 bash 手册页:

    ${参数:+word}

    使用替代值。如果 parameter 为 null 或未设置,则不替换任何内容,否则 word 的扩展为 替换。

    测试脚本:

    #!/bin/bash
    
    declare -A UsersRestrictions
    UsersRestrictions['root']=""
    UsersRestrictions['foo']="bar"
    UsersRestrictions['spaces']="    "
    
    for i in root foo spaces notset
    do
        if [[ -z "${UsersRestrictions[$i]+x}" ]]; then
            echo "$i is null"
        else 
            echo "$i is not null. Has value: [${UsersRestrictions[$i]}]"
        fi
    done
    

    输出:

    root is not null. Has value: []
    foo is not null. Has value: [bar]
    spaces is not null. Has value: [    ]
    notset is null
    

    【讨论】:

      【解决方案2】:

      尝试以下方法:

      if [[ -z "${UsersRestrictions['notset']}" && "${UsersRestrictions['notset']+x}" ]]; then
          echo "notset is defined (can be empty)"
      else 
          echo "notset is not defined at all"
      fi
      

      诀窍是连接一个虚拟的x 字符,它只会在变量 定义时附加(无论它是否为空)。另请注意,root 的第一个测试应该给您root null,因为该值实际上是空的。如果要测试该值是否为空,请改用if [[ ! -z $var ]]

      DEMO.

      参考资料:

      【讨论】:

      • -n 似乎也将空字符串视为空字符串。试试看:test ! -n "" && echo true
      猜你喜欢
      • 2023-03-12
      • 2023-04-10
      • 2020-01-31
      • 2018-09-27
      • 1970-01-01
      • 1970-01-01
      • 2018-12-26
      • 2018-10-18
      • 1970-01-01
      相关资源
      最近更新 更多