How to test if a parameter has been set to the empty string?

Tim*_*Tim 1 bash variable

I want to test if a parameter is an empty string "".

When the parameter is not set, the test should fail.

  1. Why does the following not succeed?

    $ unset aa
    $ if [ ${aa}=="" ]; then echo yes; else echo no; fi
    yes
    
    Run Code Online (Sandbox Code Playgroud)
  2. What shall I do instead?

Kus*_*nda 6

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 variable VAR 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}将扩展为。valuevariable

请注意,非常相似的${variable:-value}将扩展为valueif variableis unset或 null(空字符串)。

  • @isaac 它被标记为`bash`。 (2认同)