~> if [ -z $FOO ]; then echo "EMPTY"; fi
EMPTY
~> FOO=""
~> if [ -z $FOO ]; then echo "EMPTY"; fi
EMPTY
~> FOO="a"
~> if [ -z $FOO ]; then echo "EMPTY"; fi
~>
- z 也适用于未定义的变量。为了区分未定义的和已定义的,你可以使用列出的 给你或者更清楚的解释 给你。
最简洁的方法是像这些例子一样使用扩展。要获得所有选项,请查看手册中的参数扩展部分。
备选词:
~$ unset FOO
~$ if test ${FOO+defined}; then echo "DEFINED"; fi
~$ FOO=""
~$ if test ${FOO+defined}; then echo "DEFINED"; fi
DEFINED
默认值:
~$ FOO=""
~$ if test "${FOO-default value}" ; then echo "UNDEFINED"; fi
~$ unset FOO
~$ if test "${FOO-default value}" ; then echo "UNDEFINED"; fi
UNDEFINED
if [ -z "${VAR+xxx}" ]; then echo "VAR is not set at all"; fi
这样不也一样吗?
if [ -z "${VAR}" ]; then echo "VAR is not set at all"; fi
合理的问题——答案是“不,你更简单的选择不会做同样的事情”。
假设我在您的测试之前写下这些:
VAR=
您的测试将说“ VAR 根本没有设置”,但是我的测试将说(暗示因为它没有回应任何内容)“ VAR 已经设置,但是它的值可能是空的”。试试这个脚本:
(
unset VAR
if [ -z "${VAR+xxx}" ]; then echo "JL:1 VAR is not set at all"; fi
if [ -z "${VAR}" ]; then echo "MP:1 VAR is not set at all"; fi
VAR=
if [ -z "${VAR+xxx}" ]; then echo "JL:2 VAR is not set at all"; fi
if [ -z "${VAR}" ]; then echo "MP:2 VAR is not set at all"; fi
)
输出结果是:
JL:1 VAR is not set at all
MP:1 VAR is not set at all
MP:2 VAR is not set at all
[ -n "$var" ] && echo "var is set and not empty"
[ -z "$var" ] && echo "var is unset or empty"
[ "${var+x}" = "x" ] && echo "var is set" # may or may not be empty
[ -n "${var+x}" ] && echo "var is set" # may or may not be empty
[ -z "${var+x}" ] && echo "var is unset"
[ -z "${var-x}" ] && echo "var is set and empty"
当使用“ set-o nounset” 包含一个更好的答案(一个可读性更好且启用 set -o nounset的答案)时,测试 bash 中是否设置了一个变量。它的工作原理大致如下:
if [ -n "${VAR-}" ]; then
echo "VAR is set and is not empty"
elif [ "${VAR+DEFINED_BUT_EMPTY}" = "DEFINED_BUT_EMPTY" ]; then
echo "VAR is set, but empty"
else
echo "VAR is not set"
fi