DEV Community

Serhat Teker
Serhat Teker

Posted on • Originally published at tech.serhatteker.com on

How to Add Path Uniquely to $PATH

There are 2 easy options for this: Add as a "configuration" or a "function".

Configuration

Add below 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.

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

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

For instance add ~/projects dir to $PATH:

[[ ":$PATH:" != *":${HOME}/projects:"* ]] && PATH="${PATH}:${HOME}/projects"
Enter fullscreen mode Exit fullscreen mode

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

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
}
Enter fullscreen mode Exit fullscreen mode

It will check whether the path given is already in the $PATH and also lets you append it "after" or "before" to $PATH 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
Enter fullscreen mode Exit fullscreen mode

All done!

Top comments (0)