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 VARTrue if the shell variableVARis set.
Or, from the bash manual's "CONDITIONAL EXPRESSIONS" section:
-v varnameTrue if the shell variable
varnameis 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}将扩展为。valuevariable
请注意,非常相似的${variable:-value}将扩展为valueif variableis unset或 null(空字符串)。
| 归档时间: |
|
| 查看次数: |
4979 次 |
| 最近记录: |