UNDERSTANDING BASH STARTUP FILES

The bash shell uses a variety of startup files, which are roughly analogous to the Autoexec.bat file on MS-DOS systems. What confuses more than a few Linux users is that bash (unlike MS-DOS) uses more than one startup file. Often, bash users have trouble figuring out which file they should use for new, automatically executed commands.

Here's a quick review of the startup files that bash can use, followed by a discussion of just when these startup files come into play. Note that the tilde (~) stands for your home directory.

The /etc/profile is the main startup file for bash. Because it is located in the /etc directory, which should be readable for all system users, it is used for commands that all users need. In contrast, a user's home directory contains one or more of the following bash startup files, which contain commands that apply only to the current user's bash session: ~/.bash_profile, ~/.bash_login, ~/.profile, ~/bash_rc, and ~/.bash_logout.

To understand how bash employs the various user startup files, you must understand the difference between a login shell and a nonlogin shell. A login shell is created when you log in to your Linux account. A nonlogin shell is created when you launch an additional bash shell within your user session, as you do when you open a terminal window in X.

When you start a login shell, bash consults the following files in the specified order:


/etc/profile


~/.bash.profile


~/.bash_login


~/.profile

When you start a nonlogin shell, bash consults only one startup file, ~/bash.rc.

Because login and nonlogin shells use different startup files, both shells may differ. Most Linux distributions contain an automatically generated ~./bash_profile that contains a script that automatically executes the commands placed in ~/bash_rc. This script ensures that the login shell will be configured like the nonlogin shell. Although this script is useful, a full understanding of the way bash works with startup files is needed if you wish to understand just where you should add commands to a bash startup file.

To add a command that is automatically executed when any user begins a login shell, add the command to /etc/profile. You'll need to switch to superuser status to edit this file.

To add a command that is executed when you start a login shell in your own user account, use ~/bash.profile for commands that must be executed before commands contained in ~/.bash_login or ~/profile. Use ~/.profile for commands that must be executed only after the shell executes the commands found in ~/.bash.profile and ~/bash_login.

To add a command that is executed when you start a nonlogin shell, use ~/.bashrc.