Friday, January 22, 2010

.bashrc vs. .bash_profile

One continuing source of confusion among bash users is the question "Where should start-up settings go?"

As you may recall, bash reads startup files when it starts.  These startup files are used to establish the user's environment including environment variables like PATH, command aliases, and programs to launch when the user logs in.

Shell sessions can be divided into two different types: login shells and non-login shells.  bash uses different startup files for each type.

A login shell occurs when the user is prompted for a user name and password.  Examples include virtual consoles (accessed by pressing Ctrl-Alt-F1 through Ctrl-Alt-F6) and terminal sessions on remote hosts using ssh or telnet.

A non-login shell is typically a terminal session launched on the graphical desktop.

Startup files can also be divided into two groups: global and personal.  Global startup files are located in the /etc directory and apply to all users while personal startup files are located in each user's home directory.

So let's look at which files are read for each type of shell session:

Non-Login Shells

bash reads and executes the global startup file /etc/bash.bashrc followed by the personal file ~/.bashrc if they exist.

Login Shells

bash reads and executes the global startup file /etc/profile if it exists.  Next, it attempts to read and execute ~/.bash_profile, ~/.bash_login, and ~/.profile in that order, stopping after the first file is found.  Red Hat distributions by default supply ~/.bash_profile, while Debian distributions (such as Ubuntu) use ~/.profile.

Adding Your Own Settings

If you study the contents of either ~/.bash_profile or ~/.profile, you will see that both files source (i.e., read in the contents of) the ~/.bashrc file.  This means that ~/.bashrc is read during the startup of both login and non-login shells, so putting your changes in ~/.bashrc is usually a safe bet.

Further Reading

The Linux Command Line covers this in Chapter 12.

The INVOCATION section of the bash man page contains a full description of the the bash startup process.