Pathmunge
This one came from reading RHEL4U3′s default /etc/profile today. Before you call me a nerd and go back to your so called life, hear me out on this. So, the good folks in Raleigh decided to add a function called pathmunge to their default profile. This function just allows you to type stuff like pathmunge ~/bin after to add a directory to your search path. Most self-respecting nerds probably sorted this out in 1987, however, I’m an idiot and continue to do things the old fashioned way until I’m bludgeoned with the technology stick. Unfortunately, pathmunge doesn’t get added to the default shell environment for all users. So, I just added it to /etc/bashrc on my machines today. Here is how to implement pathmunge in all of its glory…
pathmunge () {
if ! echo $PATH | /bin/egrep -q "(^|:)$1($|:)" ; then
if [ "$2" = "after" ] ; then
PATH=$PATH:$1
else
PATH=$1:$PATH
fi
fi
}
Feel free to throw this into your ~/.bashrc if you haven’t implemented it already.
Trackbacks
Use this link to trackback from your own site.







1. what does ! echo $PATH do?
2. does “|” == “OR”
3. i can’t tell how this updates your profile.
Yeah, I have no idea what you’re talking about.
All that pathmunge does is sets up a bash function to add directories to the beginning or at the end of your
$PATHBefore:
pathmunge ~/binwould setPATH=~/bin:$PATHAfter:
pathmunge ~/bin afterwould setPATH=$PATH:~/binThe egrep nonsense at the beginning is to make sure that the path doesn’t already exist in your path (prevents you from adding it twice, aliases notwithstanding). The parentheses and | character in a regular expression is indeed a logical OR operation. E.g. (Jer|Ch)rome would match Jerome and Chrome. These operations fall into the realm of extended regular expressions which is why the author rightly called egrep. The $ and ^ in a regex means beginning of line and end of line. So, the egrep stuff is just a low rent way of parsing a colon delimited $PATH. If you add this function to your ~/.bashrc or /etc/bashrc, bash treats it as a command that can be invoked from the command-line.
my question 2 was in regards to the first “|”, but now i see that you pipe the echo to the egrep then the ! refers to the final output…life’s hard without parenthese!
That’s a pipe, man. Come on, get with the program…
NO!
The pathmunge() above dosen’t work – it always adds its first argument to PATH, even if it is already present.
The problem is in the argument to egrep which is quoted with single quotes so the $1 doesn’t get expanded. This means that egrep doesn’t search PATH for the first argument, instead it searches literally for ‘$1′.
The fix is to use double quotes like this “(^|:)$1($|:)” instead of ‘(^|:)$1($|:)’
Normally I wouldn’t be such a pedant but this page is the top hit when googling for “pathmunge” :-)