3

我无法找出如何在 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'。但我在这两种情况下都得到了相同的结果。我已经搜索了其他可能的方法,但到目前为止都给了我相同的结果。有没有办法做到这一点?

谢谢!

4

2 回答 2

3

Use -z ${parameter:+word} as your test condition. It will always be true if parameter is null or unset, otherwise it will be false.

From the bash man page:

${parameter:+word}

Use Alternate Value. If parameter is null or unset, nothing is substituted, otherwise the expansion of word is substituted.

Test script:

#!/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

Output:

root is not null. Has value: []
foo is not null. Has value: [bar]
spaces is not null. Has value: [    ]
notset is null
于 2012-09-26T10:52:04.637 回答
0

尝试以下操作:

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 ]]改用。

演示

参考:

于 2012-09-26T10:21:52.777 回答