Environment Variables – Finding Files Setting or Adding Variables and Their Precedence

environment-variables

Some of my environment variables ($PATH, $MANPATH and friends) are partially set up in different source files.

I find myself wishing for a command or method to quickly gather what part, in a specific environment variable, came from what file.

My $PATH, for instance, has obviously been set (added to) in .bashrc, /etc/paths, /etc/paths.d/X11 … and I'm still looking for that last mysterious file which superfluously created a duplicate path definition in my $PATH.

It takes a good while to manually pinpoint the files that contribute to environment variables. There must be a useful way to bypass this unnecessary labor of tracing all the setters … or am I the only one thinking along these lines?

Best Answer

Typically PATH is set to an initial value in a highly system-dependent way by the program that logs you in (pam_env is a common contributor), then /etc/profile and ~/.profile and files that they include go on to modify that value.

Remove any change to PATH in .bashrc, environment settings don't belong in .bashrc: see Difference between .bashrc and .bash_profile.

First try logging in in text mode (e.g. with ssh localhost), as the session startup is a lot simpler than in graphics mode.

Put set -x at the beginning of /etc/profile and ~/.profile. The shell will print a trace of what it does on its standard error stream; look for assignments to PATH in the trace.

There is no notion of precedence to environment variable assignments: whoever assigns last wins.

Related Question