I want to test if a parameter is an empty string ""
.
When the parameter is not set, the test should fail.
Why does the following not succeed?
$ unset aa
$ if [ ${aa}=="" ]; then echo yes; else echo no; fi
yes
Run Code Online (Sandbox Code Playgroud)What shall I do instead?
Your (attempted) test $aa == ""
is equivalent of comparing two empty strings with each other, which results in a true result. This is because the shell will expand unset variables to the empty string. Without the spaces around the ==
, the test will always be true as it's the same as testing on the two character string ==
. This string is always true.
Instead, in bash
:
$ unset aa
$ if [ -v aa ]; then echo Set; else echo Not set; fi
Not set
$ aa=""
$ if [ -v aa ]; then echo Set; else echo Not set; fi
Set
Run Code Online (Sandbox Code Playgroud)
The full test for an empty string would therefore be
if [ -v aa ] && [ -z "$aa" ]; then
echo Set but empty
fi
Run Code Online (Sandbox Code Playgroud)
From help test
in bash
:
-v VAR
True if the shell variableVAR
is set.
Or, from the bash
manual's "CONDITIONAL EXPRESSIONS" section:
-v varname
True if the shell variable
varname
is set (has been assigned a value).
通过-v
测试,您测试变量的名称而不是它的值。
如果你真的想做一个字符串比较,你可以做类似的事情
if [[ "${aa-InvalidValue}" != "InvalidValue" ]] && [ -z "$aa" ]; then
echo Set but empty
fi
Run Code Online (Sandbox Code Playgroud)
如果未设置,扩展${variable-value}
将扩展为。value
variable
请注意,非常相似的${variable:-value}
将扩展为value
if variable
is unset或 null(空字符串)。