Linux
10 April 2012 0 Comments

About .bashrc, .profile, .bash_profile and .bash_login

How it works

There are various files that may be executed by the Bash shell when it is started. Usually they follow this logic:

  • When bash is invoked as an interactive login shell:
    1. Bash first reads and executes commands from the file /etc/profile, if that file exists.
    2. 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. Usually there is a default ~/.profile file, and ~/.bash_profile and ~/.bash_login usually do not exist.
  • When bash is invoked as an interactive non-login shell:
    1. Bash reads and executes commands from /etc/bash.bashrc and ~/.bashrc, if these files exist.
    2. The standard ~/.profile sources (runs) ~/.bashrc if it exists.

A login shell means a session where you directly log into a system, e.g. setting up a remote SSH session or logging in through a non-graphical text terminal. A non-login shell is then the type of shells you open after logging in: typically in a graphical session when you open a new terminal window.

The bottom line is that you should put customisations that should always be executed in ~/.bashrc!

Example

Example: After installing Maven, the M2_HOME environment variable should be set. In order to make this persistent we put it at the bottom of the ~/.bashrc file:

# Define Maven home directory
M2_HOME=/usr/local/apache-maven/apache-maven-3.0.4
export M2_HOME
 
# Add Maven binary directory to the search path.
PATH=$PATH:$M2/bin
export PATH

Note the use of the export command to make the variables visible outside the scope of the current script. Now let’s check if we can access the variable. Start a new bash shell, then:

~$ echo $M2_HOME
/usr/local/apache-maven/apache-maven-3.0.4
 
~$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/apache-maven/apache-maven-3.0.4/bin
 
~$ mvn --version
Apache Maven 3.0.4 (r1232337; 2012-01-17 09:44:56+0100)
Maven home: /usr/local/apache-maven/apache-maven-3.0.4
Java version: 1.6.0_22, vendor: Sun Microsystems Inc.
Java home: /usr/lib/jvm/java-6-openjdk/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "2.6.38-11-generic", arch: "i386", family: "unix"

Success! Every new shell can use Maven from now on.

Note that you can also change the PATH in the /etc/environment file. This is the default PATH for every user. So by adding a directory to this PATH, it is made available across all profiles instead of only your own profile.

Tags: ,