Path Environment Variable – How It Works in Linux

environment-variablespathsession

I'm confused how the PATH environment variable works under Linux. I'm a Linux Mint 15 user.

First, I read about editing the /home/.bashrc file and doing a PATH=$PATH:/directory,
but I also knew about some path stuff managed in /etc/bash.bashrc
and so any software installed in /usr/local/bin would be reachable from anywhere in the shell.

How does the path variable work under Linux and where should it be placed?

Best Answer

The basic concept to grasp here is that PATH can be defined in many places. As @demure explains in his answer, PATH=$PATH:/new/dir means add /new_dir to $PATH, it will not clear the original $PATH.

Now, one reason there are many files is intimately connected with the concept of login and non-login shells. See here for a nice summary. The following is from the bash man page (emphasis mine):

When bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable. The --noprofile option may be used when the shell is started to inhibit this behavior.

When you first log into your system, you start a login shell so bash will read the files listed above. Most distributions set a system-wide $PATH (which applies to all users) at /etc/profile and this is where you should make any changes that you want applied to all users. This is what I have on my Debian:

PATH="/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games"

Once you have logged in, when you open a terminal you start an interactive, non-login shell. This is what man bash has to say about those:

   When  an  interactive shell that is not a login shell
   is started, bash reads  and  executes  commands  from
   /etc/bash.bashrc and ~/.bashrc, if these files exist.

So, those files are read every time you open a new terminal. Your filnal $PATH is the combination of the values in all files. In a typical situation, you log in using a graphical log in manager and start a new session. At this pòint your $PATH is whatever was defined in the various profile files. If you open a terminal, then you are in an interactive shell and the different bashrc files are read which may append things to the $PATH.


To summarize, all you really need to know is that you can make changes to your user's $PATH by editing $HOME/.profile.

Related Question