使用bash,检查变量是否为空的最佳方法是什么?
如果我使用:
if [ -z "$VAR" ]
Run Code Online (Sandbox Code Playgroud)
正如在论坛中所建议的那样,这适用于未设置的变量,但是当变量设置为空时它是正确的.建议?
gee*_*aur 34
${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
Run Code Online (Sandbox Code Playgroud)
Kev*_*eck -2
if [ `set | grep '^VAR=$'` ]
Run Code Online (Sandbox Code Playgroud)
这将在变量集列表中搜索字符串“VAR=”。