使用bash,检查变量是否为空的最佳方法是什么?
如果我使用:
if [ -z "$VAR" ]
正如在论坛中所建议的那样,这适用于未设置的变量,但是当设置变量但是为空时它是正确的。 建议?
答案 0 :(得分:32)
${var+set}
如果变量未设置则不替换任何内容,如果将set
设置为包括空字符串在内的任何内容则为${var:+set}
。仅当变量设置为非空字符串时,set
才会替换if [ "${foo+set}" = set ]; then
# set, but may be empty
fi
if [ "${foo:+set}" = set ]; then
# set and nonempty
fi
if [ "${foo-unset}" = unset ]; then
# foo not set or foo contains the actual string 'unset'
# to avoid a potential false condition in the latter case,
# use [ "${foo+set}" != set ] instead
fi
if [ "${foo:-unset}" = unset ]; then
# foo not set or foo empty or foo contains the actual string 'unset'
fi
。您可以使用它来测试这两种情况:
{{1}}
答案 1 :(得分:1)
if [ `set | grep '^VAR=$'` ]
这将在变量列表中搜索字符串“VAR =”。
答案 2 :(得分:0)
嗯,这是一种方式
$ s=""
$ declare -p s
declare -- s=""
$ unset s
$ declare -p s
bash: declare: s: not found
如果未设置变量,则会出现错误消息。
答案 3 :(得分:0)
您可以使用
进行测试 [ -v name ]
名称没有$
符号
答案 4 :(得分:0)
这仅适用于空值,而不是未设置(或有值)
private NodeStates FollowPath() {
bool targetReached;
if (targetReachable)
targetReached = WalkToTarget();
if (targetReached)
return NodeStates.SUCESS;
else
return NodeStates.FAILURE;
}
答案 5 :(得分:0)
未设置(不存在)的变量和空变量在 参数扩展 中的行为不同:
在以下示例中:
没有冒号 :
仅检查 变量存在 。
带有冒号 :
检查变量是否存在(如果存在),确保它不存在 空的。
换句话说,同时检查 变量存在 和 非空 。
${parameter:-word}
如果参数为 未设置或为空 ,则替换单词的扩展名。否则,将替换参数的值。
${parameter-word}
如果参数为 未设置 ...
${parameter:=word}
如果参数为 未设置或为空 ,则单词的扩展将分配给参数。然后替换参数的值。不能以这种方式分配位置参数和特殊参数。
${parameter=word}
如果参数为 未设置 ...
${parameter:?word}
如果参数为 未设置或为空 ,则将单词的扩展名(如果不存在单词则显示该信息)写入标准错误和shell(如果有)不互动,退出。否则,将替换参数的值。
${parameter?word}
如果参数为 未设置 ...
${parameter:+word}
如果参数为 未设置或为空 ,则不替换任何内容,否则替换单词的扩展名。
${parameter+word}
如果参数为 未设置 ...