Changing PATH variable in a more organized way.

This is more a note to self than a full post. This week I've been configuring my new laptop and again I had to configure the PATH variable for some applications and scripts.

Usually you will create a .bash_profile at your home folder and change the PATH like this:

PATH=~/bin:/some/new/application/bin:${PATH}

export PATH

Two simple Bash functions can make this more elegant, I have:

unset partial_path
_push_to_path () {
    if [ -z ${partial_path} ]; then
        partial_path=${1}
    else
        partial_path=${partial_path}:${1}
    fi
}
_export_path () {
    export PATH=${partial_path}
    unset partial_path
}

And then you can on your .bash_profile:

_push_to_path "~/bin"
_push_to_path "/some/new/application/bin"
_push_to_path $(launchctl getenv PATH)
_export_path

This is a little more organized and easy to maintain. Note the last line, on OS X you can add back the system path by asking launchctl to give you the system environment entry for PATH.

That's it.

Published in Dec 21, 2011