0

We usually write in script:

PATH="xxx"
export PATH

I know PATH is a common variable in bash, then export invokes setenv() to do something.

But why not bash export PATH automatically when PATH is assigned a value.

Is there a case someone only want to change PATH variable without exporting it? Or, some other reasons?

weiweishuo
  • 847
  • 7
  • 15

1 Answers1

2

Well, the truth is that you can in your situation omit the export statement. Try it out: Open a subshell (by typing bash), then set the PATH variable to a different value without exporting it, then open another one (this time by typing bash --norc, to avoid possible errors from .bashrc due to the changed PATH), and do a echo $PATH. You will see that the PATH variable has changed even though you had not exported it.

The reason, however, is not that PATH is in any way special (i.e. exported automatically by some internal magic of the bash shell). It is exported, because a variable, which you mark once for exporting, is put into the environment - this is what "exporting" actually means - and hence inherited by all child processes. In the case of PATH, it is very likely that some PATH has been set already in /etc/profile and of course you will find an export PATH in this file. This file is sourced whenever bash is run as login shell and hence inherited by all other processes spawned from it.

It is stil a good idea to export PATH in your own dot-files, because your bash will then be independent from the environment of the parent process. After all, it is possible to construct an example, where a interactive non-login bash shell is invoked by a process which does not have PATH in its environment.

user1934428
  • 19,864
  • 7
  • 42
  • 87
  • Thanks, I think I get your meaning, besides `PATH`, a shell user may need push other custom variables to the environment. Even if bash play tricks to make `PATH` automatically exported when assigned, it has no way to help the custom variables. – weiweishuo Nov 30 '18 at 08:43
  • It's simple and predictable to treat PATH the same as all other variables. If Bash had a list to autoexport, now all of a sudden the user has to keep in mind that which variables are autoexported by which version of which shell. More special cases, more portability problems, more useless complexity. – that other guy Nov 30 '18 at 17:13