Easy way to add paths to $PATH in bash

This little script is a convenient way to add paths to your $PATH variable without worrying about duplication. I generally break out my .bash files to be organized across multiple servers/computers and each one seems to need different paths appended – so thats where this little guy comes in handy. Just a simple push_path and no worries.

# Push a path to our $PATH variable
# Usage:
#    push_path <path> [after]
# If after is specified it will appear at the end of $PATH, otherwise it is unshifted
push_path(){
        if ! echo $PATH | egrep -q "(^|:)$1($|:)" ; then
           if [ "$2" = "after" ] ; then
              PATH=$PATH:$1
           else
              PATH=$1:$PATH
           fi
        fi
}

Usage

# Push all local/**/bin
push_path /usr/local/bin
for path in `ls -d /usr/local/*/bin 2>/dev/null`; do
        push_path $path
done

# Push ~/bin
push_path $HOME/bin

# Push /opt/bin at the end
push_path /opt/bin "after"

View Gist