2011-01-14

Bash users: tidy cluttered ".bash_aliases" files

I modify my ".bash_aliases" file all the time as I change projects, modify path, aliases, etc.  I got tired of dynamic effects doing strange things to my environment as I sourced the file often during a long session (which go days as I don't log out very often).   I would get things like:

$ env
...
# duplicate paths:
PATH=/usr/local/bin:/usr/bin:/usr/local/bin:...

So I sought a solution.  There is a common shell function to help such things and it's known as pathmunge which is discussed here:

  http://www.cyberciti.biz/faq/redhat-linux-pathmunge-command-in-shell-script/

Other solutions are available, e.g.,

  http://www.linuxjournal.com/article/3645

But none of those was just what I needed.  So I designed a Perl script to be called from my .bash_aliases when it was sourced and it did all the cleanup work.

This is how it looks inside a fragment of my current .bash_aliases file:

#=============================================
# DO NOT ADD NEW PATH DATA BELOW THIS LINE
#=============================================
# A hack to eliminate path dups, unwanted paths,and assure
# path order is correct.
# This should be at the end of this file.
ZDIR="${HOME}/tbrowde-home-bzr/0_resource_files"
P=`${ZDIR}/path_manip.pl ${PATH} -path`
export PATH=$P


The Perl script is "path_manip.pl" and it returns a modified environment variable that is fed to it.  Notice I don't export the path until the end after I've cleaned it up.   I use the Perl script on nearly all my big environment variables such as PERL5LIB and MANPATH.

By the way, I keep both the .bash_aliases file and the Perl helper under version control (and backed up).  I have recently converted to bazaar from subversion and it is easy to use--highly recommended:

  http://bazaar.canonical.com/en/

I'll discuss the innards of "path_manip.pl" and post it here later--but only if there is any interest--stay tuned.