Tuesday, June 7, 2011

Tips for Setting up OSX bash files

If you have just installed or upgraded OSX and are interested in setting up your bash environment, here's some quick tips that will enable you to load all of your setup configuration customizations into a login shell or an interactive shell from a single bash startup file.

When a login shell is created (via logging into the console, opening iTerm/xterm or opening a new iTerm tab), bash reads these startup files in this order:

1. /etc/profile
2. /etc/bashrc
3. ~/.bash_profile

HOWEVER, in step #3, bash actually looks for and reads only ONE of the following files - if found - in the following order:

1. ~/.bash_profile
2. ~/.bash_login
3. ~/.profile

If you 'ls' your home directory and find '.profile', it's okay to rename it as '.bash_profile'. I suggest going with '.bash_profile', for no other reason than the fact that .bash_profile is the first file that bash looks for in your home directory.

If you ever create an interactive shell (typically by calling 'bash' from within a login shell), the following files are read in this order:

1. /etc/bashrc
2. ~/.bashrc

So here's the deal. I want to put all of my bash environment customizations in a single file that will be executed whenever a login shell is created or when an interactive shell is created. I could put all that in /etc/bashrc, which executes for all users (not just for the current logged-in user) in both scenarios, but it's better store all bash customizations in my personal home directory. What to do?

The solution is to create ~/.bashrc and load it with your environment customizations. Then, invoke it from within the one user-specific bash file that you know will always be executed when a login shell is created: either ~/.profile or ~/.bash_profile (depending on which one you prefer).

Somewhere in your .bash_profile (or .profile) file - preferably at the bottom (after the paths are exported) - add this line:

source ~/.bashrc

This command invokes ~/.bashrc within the current login shell. Because ~/.bash_profile (or ~/.profile) is always executed when a new login shell is created, your .bashrc customizations will always be loaded into the shell.

And, remember that when you start an interactive shell within a login shell, bash will invoke ~/.bashrc automatically.

For more details and cool customization tips for .bashrc, see http://blog.toddwerth.com/entries/4