Unexporting enviromental variable

2019-09-13 01:20发布

问题:

I have a variable

pathname="xxx"

I have set it as an enviroment variable using

export pathname="xxx"

How do I "reverse" it and make the variable not exported?

回答1:

In bash you can use typeset (or its synonym declare) to remove the export attribute.

$ export foo=3
$ bash -c 'echo $foo'
3
$ typeset +x foo
$ bash -c 'echo $foo'

$

(The same command works in zsh and ksh. You can use declare in either bash or zsh, but not ksh, and it is probably more common to see it used in practice.)

As far as I know, there is no way to remove the export attribute in POSIX shell. (dash is a prominent example of a shell which does not provide an extension such as declare.) You would need to save the value in a temporary value, unset the original, then reset the original:

$ export foo=3
$ tmp=$foo
$ unset foo
$ foo=$tmp
$ echo "$foo"
3
$ sh -c 'echo $foo'

$

(dash, at least, explicitly documents that the only way to remove the export attribute is to unset it.)



标签: shell unix