Unsetting environment variable with an empty name

environment-variables

For some reason, my system sets an environment variable with no name. This can be seen in the output from printenv as a line containing only = and causes problems for Python (more specifically the os.environ object).

How do I unset this environment variable? Is there any other workaround (e.g. prevent the variable to be set in the first place)?

To reproduce do e.g. env -i printenv, or for the Python problem do env -i = python -c "import os; os.environ.clear()"

Best Answer

Environment variables aren't supposed to have an empty name, so many utilities don't support them.

The env command from GNU coreutils supports setting the environment variable with an empty name but not unsetting it. That's a bug.

$ env '=wibble' env |grep wibble                                 
=wibble
$ env '=wibble' env -u '' env
env: cannot unset `': Invalid argument

Common shells can't unset the empty name either. That's ok, since the empty name isn't supposed to be used as an environment variable, and can't be used as a shell variable. Zsh is the only buggy one in the lot: it pretends to do the job but in fact does nothing.

$ env '=wibble' dash -c 'unset ""'
dash: 1: unset: : bad variable name
$ env '=wibble' bash -c 'unset ""'
bash: line 0: unset: `': not a valid identifier
$ env '=wibble' ksh -c 'unset ""'
ksh[1]: unset: : invalid variable name
$ env '=wibble' mksh -c 'unset ""'
mksh: : is read only
$ env '=wibble' posh -c 'unset ""'
posh: unset:  is read only
$ env '=wibble' zsh -c 'unset ""'
$ env '=wibble' zsh -c 'unset ""; env' | grep wibble
=wibble

Python, as you've noticed, bugs out when it finds the empty name for an environment variable.

Perl has no such problem, so it may be a solution for you. Note that you have to execute a new shell to use an external process to change the environment.

perl -e 'delete $ENV{""}; exec $ARGV[0] @ARGV' "$SHELL" "-$-"
Related Question