我在查找如何在 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"的测试给我"不空","notset"的测试给我"空"。但在这两种情况下我都得到了相同的结果。我已经搜索了其他可能的方法,但到目前为止都给了我相同的结果。有没有办法实现这一目标?
谢谢!
使用 -z ${parameter:+word}
作为测试条件。如果参数为 null 或未设置,则始终为 true,否则将为 false。
从 bash 手册页:
${参数:+字}
使用备用值。 如果参数为 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
尝试以下操作:
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 ]]
。
演示。
引用:
- 高级 Bash 脚本指南:其他比较运算符