Configuration

Add a path to $PATH if it is not already in $PATH:

[[ ":$PATH:" != *":/path/to/add:"* ]] && PATH="${PATH}:/path/to/add"

For instance add ~/projects dir to $PATH:

[[ ":$PATH:" != *":${HOME}/projects:"* ]] && PATH="${PATH}:${HOME}/projects"

If you need it at the start use PATH=/path/to/add:${PATH} instead of PATH=${PATH}:/path/to/add.

Add this into your .profile/.bash_profile/.zprofile. You can add it into .bashrc/.zshrc as well but I do not prefer this method. Since environment variables should be set in ~/.profile.

Function

Also you can use a function to do this:

path-append () {
        if ! echo "$PATH" | /bin/grep -Eq "(^|:)$1($|:)" ; then
           if [ "$2" = "before" ] ; then
              PATH="$1:$PATH"
           else
              PATH="$PATH:$1"
           fi
        fi
}

It will check whether the path given is already in the $PATH and also lets you add it to the “end” or the “beginning” as desired —default is “after”:

For example:

$ echo $PATH
/usr/local/bin:/usr/bin:/bin

## Add to the end; default
$ path-append /sbin
$ echo $PATH
/usr/local/bin:/usr/bin:/bin:/sbin

## Add to the start
$ path-append /usr/sbin before
$ echo $PATH
/sbin:/usr/local/bin:/usr/bin:/bin

All done!