Bash

It is often convenient to load environment variables and other configurations every time you launch a bash shell. The question arises which startup files need to be configured in order achieve this. In fact, there is quite a large collection of startup files that may or may not be loaded by the shell, depending on a number of parameters. For novice users, this soup of configuration files may come across as quite a mess, and perhaps it is. Lets first specify the most common configuration files, and then discuss each of its functions.

~/.bashrc
~/.bash_profile
~/.bash_login
~/.profile
/etc/profile

Before I tell you about the specific startup files, it is important that you first understand the distinction between different types of shells. Essentially there are two modes of the bash shell: the login shell and the non-login shell. The login shell normally is loaded after successfully logging in using /bin/login, and typically is the type of shell you run when you log into a server using ssh. The non-login shell is typically started by calling /bin/bash. Login and non-login shell load different startup files. This may make sense to you, as you probably can imagine that when a user logs in, you want the system to do more extensive initialization, and perhaps even show a welcome message, whereas when a user is already logged in and opens yet another shell, you want it to be lightweight and fast.

When bash is invoked as a login shell, it runs the /etc/profile startup file. Then it looks for the files ~/.bash_profile, ~/.bash_login and ~/.profile, in that order, and executes the commands from the first file that is present.

When bash is invoked as a non-login shell, it runs the ~/.bashrc configuration file.

It could very well be that you want to add directories to your $PATH, and specify aliases that apply to both to login and non-login shells. If this is the case, there is an easy hack. You could instruct ~/.bash_profile to execute the commands specified in ~/.bashrc by adding the following lines to your ~/.bash_profile file.

if [ -f ~/.bashrc ]; then
  source ~/.bashrc
fi

Now, you only have to specify the $PATH variable; your aliases and all other common shell configurations in the ~/.bashrc startup file.

Copyright 2013 by Mark Teisman.
Content licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.