makansij
makansij

Reputation: 9875

Why does "unset" work on environmental variables?

It was my understanding that set is for setting shell variables. And.. it was my understanding that export is for setting environmental variables.

So, is there any good reason why unset will delete environmental variables, but not shell variables?

E.g. when I export a variable via export VAR='something' I can then do unset VAR and I do printenv, and I see that it isn't listed anymore.

However, I can't find the equivalent for deleting local variables? Or is unset a misnomer? Thanks.

Upvotes: 0

Views: 95

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 754710

unset VAR will unset the variable whether it be local or environmental. Try:

$ set | grep '^VAR='
$ VAR=xyz
$ set | grep '^VAR='
VAR=xyz
$ unset VAR
$ set | grep '^VAR='
$

Note that VAR appears in the first lot of output from set and not in the second.

For historical reasons if nothing else, you can create a variable, then export it. Bash seems to have an inordinately elaborate output format for export which is reflected in the revised grep in the test below:

$ unset VAR
$ export | grep '^declare -x VAR='
$ VAR=xyz
$ set | grep '^VAR='
VAR=xyz
$ export | grep '^declare -x VAR='
$ export VAR
$ export | grep '^declare -x VAR='
declare -x VAR="xyz"
$ unset VAR
$ export | grep '^declare -x VAR='
$

The set command in Bourne shell and its derivatives (POSIX, Korn, Bash, etc) has very little to do with variables at all.

Upvotes: 1

Related Questions