Wednesday, October 21, 2009

.bash_profile vs. .bashrc

There are many subtleties in the way shells start up and what they automatically source when they do. At one point I had to have this down pat for my job, for both Red Hat Linux systems and HP-UX systems. It has gotten a little fuzzy since then, but I rediscovered this basic point today: profile files are sourced once when you log in, your rc file is sourced every time you start a shell.

But what does that mean? If you put something like this in your .bashrc:

export PATH=$PATH:/home/username/bin

And start up, say, a gnome-terminal, your PATH will have /home/username/bin appended to it. To see it type this:

echo $PATH

Good enough. Now, in that gnome-terminal, if you execute something that causes another sub shell to be spawned (like, you execute a script), your .bashrc will be sourced again, and that export statement will execute again. Try typing this in your gnome-terminal:

bash # starts a subshell
echo $PATH

See /home/username/bin repeated twice? That’s really not what you want to happen. That’s why you want to export environment variable in your .bash_profile, not your .bashrc. I don’t like logging out of my desktop session and logging back in to effect changes made to my .bash_profile, so I go into my gnome-terminal preferences under Title and Command and check the box next to “Run command as a login shell.” That way every time a gnome-terminal starts up, it’s acts like a new login. It starts up with a clean environment and it sources my .bash_profile. Then I add this at the end of my .bash_profile to make sure my .bashrc gets sourced too:

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

I'm sure my former self could have explained this better and with more precision, but for what most command-line junkies do, this should be sufficient.

4 comments:

semente said...

Today I published my bash settings in Bitbucket, see: http://bitbucket.org/semente/bash/src

I hope it is useful to you.

Luke said...

So wouldn't it make sense to put most of the config stuff into .bash_profile and only keep the PS1 defintion, say, in .bashrc?

Bryan said...

I found some old notes, and I wrote that the only thing you should *not* put in your .bach_profile are aliases and functions.

Bryan said...

Here's some more info on this topic that I just found:

http://benakiva.blogspot.com/2006/09/ubuntu-bashprofile-does-not-get-run-at.html