使用 bash,检查变量是否为空的最佳方法是什么?
如果我使用:
if [ -z "$VAR" ]
正如论坛中所建议的那样,这适用于未设置的变量,但当变量已设置但为空时它是正确的。 有什么建议吗?
最佳答案
如果变量未设置,
${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
关于bash - bash中未设置和空变量之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5406858/