Difference between setting an environment variable to the empty string and unsetting it

environment-variables

Is there any practical difference between unsetting an environment variable and setting it to the empty string?

Best Answer

Each application is free to interpret an unset variable and an empty variable in the same way or not. It is generally a bad idea to give them different meanings, and most applications don't do it, but it happens.

An example in shells themselves is the IFS shell variable (which is usually not exported in the environment, but the same principle applies). If unset, the shell behaves as if the value was $' \t\n'.

In a shell script, $foo expands to an empty string whether foo is set to an empty value or unset. You can run the shell under the nounset setting (set -u or set -o nounset), in which case the shell reports an error and exits if you try to expand an unset variable. Otherwise, you can distinguish between unset and empty variables with parameter expansion modifiers: ${foo:+a} expands to a if foo is unset or empty and to the empty string otherwise, whereas ${foo+a} expands to a even if foo is set to the empty string.