bash_profile or bashrc?

I'm setting up my systems at work which includes setting up my session terminal windows on various Linux servers.  At times like these, the question runs through my mind as to which configuration file to use for my login scripts, .bash_profile or .bashrc. For my Windows readers, we're talking Linux today.

We're also talking the BASH shell here, not the CSH or KSH, although they have similar files on start up.  A shell is a terminal window with a command line prompt that you see when you login to a Linux server.  It gives you a command line interface to the Linux operating system, as opposed to a desktop like you have in Windows.

So when do you use one or the other?

When you first login to a Linux shell, you want a way to run shell commands, set your PATH, and set environmental options for that paricular server session.  The .bash_profile file is run when your first open your terminal window, or any window, that requires you to login.

Actually, when you first login, the shell first looks for an /etc/profile file, and if it exists, the shell runs it first.  This is where you would put set up variables that would apply to all users.

Then, the shell looks for one of three files in order: ~/.bash_profile, then ~/.bash_login, and then ~/.profile.  It will only run the first one of the three files it finds.  Since the ~/.bash_profile is the first file looked for, after the shell looks for /etc profile, it is the file everyone uses for login scripts.

There is another file that runs when you open a new terminal window that doesn't require you to enter a user name and password, ~/.bashrc.  When would this be run?

If you are in a GNOME or KDE desktop and open a terminal window, you normally don't need to login to the terminal window, and therefore, ~/.bash_profile will not run, but ~/.bashrc will run. If you don't use a desktop, just the terminal window, and want to open another shell window with xterm, openvt, or GNU screen, for example.  If the new terminal window, or shell, doesn't require a login, then ~/.bash_profile will not run in the new window, but ~/.bashrc will.

The common practice is to put your shell scripts in the ~/.bashrc file, and then call the ~/.bashrc file when ~/.bash_profile runs during the login.

How do we set this up?

The recommended script in the BASH manual to put in your ~/.bash_profile file that starts the ~/.bashrc file is;

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

This can be put at the beginning or the end of the .bash_profile file.

When you login, the .bash_profile file is run, which then points to and runs the .bashrc file where all your environmental set ups and aliases should reside.

By the way, there is a file run when the login shell exits at the close of a session, ~/.bash_logout, if you'd like to close things up.

Comments are closed.