0

What's the most defensive/robust/portable/paranoid way to unset an environment variable in a script?

I'm trying to avoid using an external tool to clear environment variables like in env -i some-command or perl -e 'delete $ENV{SOME_VARIABLE}; exec("some-command")' if I can avoid it.

As of right now, I'm using

export SOME_VARIABLE; unset -v SOME_VARIABLE

which, I believe, removes SOME_VARIABLE even if there's a shell variable or shell function with the same name. (although it does clobber the shell variable if it exists).

2
  • Already related, but linking for more context: unix.stackexchange.com/a/388852/117549
    – Jeff Schaller
    Commented Sep 6, 2017 at 0:38
  • Not a fully general answer, but for many tools and many environment variables an empty (null) value operates the same as an absent one, in which case you can just run SOME_VARIABLE= some-command (note the space).
    – Wildcard
    Commented Sep 6, 2017 at 4:28

1 Answer 1

4

unset SOME_VARIABLE removes SOME_VARIABLE from the environment. That's all you need in almost all cases. In the rare case where this isn't good enough, you can't escape calling an intermediate process (but it can be another instance of sh).

Calling export and then unset -v doesn't have any advantage. It's pointless to export the variable if you're going to unset it afterwards. Functions are not stored in the environment so unset -v doesn't affect what subprocesses will see.

Some shells do export functions through the environment, but they do it by encoding the function definition as a variable definition. If the variable has the same name as the function then unset FUNCTION_NAME will take care of it and if not then unset -v FUNCTION_NAME doesn't do anything more than what unset FUNCTION_NAME does.

One edge case where you can't unset a variable is if it's been declared as read-only. There's no portable way to turn a variable back from read-only to normal. To remove a read-only variable from the environment portably, you have to invoke another copy of the shell:

readonly foo=bar
export foo
sh -c 'unset foo; exec some-command'

Another edge case is a few variables that some shells insist on defining and silenly prevent from being unset. To remove those from the environment, you have to use another shell or a utility like env as s stepping stone.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .