Adding directories to the PATH in Bash
When I am working on a Linux machine for which I don’t have administrator rights and want to use a program that is not available, or even a newer version of a program that’s already installed, I just install it somewhere in my home directory and add the directory where it is stored to the PATH environment variable. If I want to override an existing version of a program that is already in the system, I will have to prefix my program’s directory to the PATH, so that it is found before its system wide counterpart. If I just want to add some functionality that was not available, I can either prefix or append the directory to the PATH. The usual way to do is is to add lines like these to the shell configuration file (.bashrc for my beloved Bash).
export PATH=$PATH:/home/jdevera/mybinaries
I find this a bit unpleasant to read, so I use these functions instead:
{
directory=`echo $1 | sed 's#/$##'` # remove trailing slash
where=$2
# Add only existing directories
if [ ! -d $directory ]; then
return 1
fi
# If the directory is already in the path, remove it so that
# it can be inserted in the desired position without
# poluting $PATH with duplicates
newpath=`echo $PATH | tr ':' '\n' | \
grep -v "^$directory\$" | \
xargs | tr ' ' ':'`
if [ $where = "beg" ]; then # Prefix to $PATH
export PATH=$directory:$newpath
elif [ $where = "end" ]; then # Append to $PATH
export PATH=$newpath:$directory
else
return 1
fi
return 0
}
# Convenience wrappers for addtopath
#
function pathappend { addtopath $1 end; return $?; }
function pathprepend { addtopath $1 beg; return $?; }
The main function, addtopath, is smarter than the previous option (exporting the new value):
- It checks that the directory exists before adding it to the PATH
- It avoids duplicates in the PATH; if the directory is already in the $PATH, it is removed prior to reinsertion. This means that the directory will be moved within PATH to the desired position
- It can prefix or append the directory to the PATH
I have also written two small wrappers, pathprepend and pathappend, that prefix and append, respectively, a directory to the PATH, thus making the calls even easier and more legible.
I can now write something like this:
pathprepend /home/jdevera/myoverrides
And will get them both in the PATH like this:
jdevera@aurora:~$ echo $PATH /home/jdevera/myoverrides:/usr/local/bin:/usr/bin:/bin:/usr/games:/home/jdevera/mynewbinaries
Edit: I added semicolons after the return statements in the wrapper functions and this now works on the Korn shell as well.




¡Y ahora en ksh! jejeje ¡friiiiiiiiki! A propósito… me he partido: http://www.43things.com/person/jovianjake la #16… (como ves he seguido el link de lo que sabe google de ti)
@N, After a little modification, this now works for ksh too.