How does the path environment variable work in Linux?

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.


In your home dir, it would be .bashrc, not .bash.rc.
The system wide config is /etc/bashrc not /etc/.bash.rc.

Unix and linux do not use \some\path\here file paths, they use /some/path/here file paths. \ is an escape character, and is used to disable other special characters.

You could edit your $PATH by adding these to lines to your ~/.bashrc (~ means your home dir)

PATH=$PATH:/usr/local/bin:/some/other/path
export PATH

Where

  • $PATH preserves anything already set to the PATH.
  • : separates entries.
  • And the two directories are examples (you don't need the :/some/other/path part)

I would not suggest editing your system wide /etc/bashrc if you only need changes for yourself.