I added this to my .bash_profile but I neglected to label it and forgot what it means exactly

I remember broadly what it does, but not specifically:

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

What is the exact purpose for it again?


Solution 1:

This sources a ~/.bashrc file if it exists and loads the contents of that file.

The short answer to your question is: you did this so no matter how you get to your machine, via a shell opened in an interactive desktop session or an ssh login to the machine, your bash shell has a consistent setup to it.

The longer answer for why you had to do it this way lies below...

The reason you'd want to do this is steeped in bash history: one of those files is used for interactive logins, the other is used for non-interactive logins. The thought behind having two different setups is you might want some things in your interactive shell (a fancy prompt, a message of the day, colourization of your command output, etc.) that you wouldn't want in a non-interactive session because it trips up programmatic access to input and output and what not.

For most users though you want both environments to be the same. Most of us aren't running complicated enough bash setups to warrant separating out interactive and non-interactive setups like this.

The .bash_profile is executed for login shells, while .bashrc is executed for interactive non-login shells.

There's a nice article by Josh Staiger that talks about why one over the other and how to remember where to put things. Allow me to quote some of it here:

What is a login or non-login shell?

When you login (type username and password) via console, either sitting at the machine, or remotely via ssh: .bash_profile is executed to configure your shell before the initial command prompt. But, if you’ve already logged into your machine and open a new terminal window (xterm) inside Gnome or KDE, then .bashrc is executed before the window command prompt. .bashrc is also run when you start a new bash instance by typing /bin/bash in a terminal.

Mac OS X — an exception

An exception to the terminal window guidelines is Mac OS X’s Terminal.app, which runs a login shell by default for each new terminal window, calling .bash_profile instead of .bashrc. Other GUI terminal emulators may do the same, but most tend not to.

Recommendation

Most of the time you don’t want to maintain two separate config files for login and non-login shells — when you set a PATH, you want it to apply to both. You can fix this by sourcing .bashrc from your .bash_profile file, then putting PATH and common settings in .bashrc.

To do this, add the following lines to .bash_profile:

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

Now when you login to your machine from a console .bashrc will be called.