Add path to $PATH if not already in $PATH

I need to add a path in a bash script, but it may be executed several times:

export PATH=${OPENSHIFT_HOMEDIR}/app-root/runtime/bin/:${PATH}

I don’t want that path to be added over and over. How can I add it if it is not in $PATH yet?

First check if the path to add is already part of the variable:

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

If /path/to/add is already in the $PATH, then nothing happens, else it is added at the beginning.

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

Edit: In you case it would look like this:

[[ ":$PATH:" != *":${OPENSHIFT_HOMEDIR}/app-root/runtime/bin:"* ]] && PATH="${OPENSHIFT_HOMEDIR}/app-root/runtime/bin:${PATH}"
Answered By: chaos

The sysadmin in my old lab had a nifty little function for this:

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

It will both check whether the string given is already in the PATH and also lets you add it to the end or the beginning as desired:

$ echo $PATH
/usr/local/bin:/usr/bin:/bin
$ pathmunge /sbin/             ## Add to the start; default
$ echo $PATH
/sbin/:/usr/local/bin:/usr/bin:/bin
$ pathmunge /usr/sbin/ after   ## Add to the end
$ echo $PATH
/sbin/:/usr/local/bin:/usr/bin:/bin:/usr/sbin/

I have this function in my ~/.profile and use it to modify my $PATH.

Answered By: terdon

With GNU sed you can do it by

echo ${PATH} | 
    sed "|${OPENSHIFT_HOMEDIR}/app-root/runtime/bin|
        ! s|^|export PATH=${OPENSHIFT_HOMEDIR}/app-root/runtime/bin:|e"
Answered By: Costas

If it’s the same string, then just do it:

set -a -- "$OPENSHIFT_HOMEDIR/app-root/runtime/bin/"
PATH=$1:${PATH#"$1:"}
set +a --

You can do that over and over and the value of $PATH won’t change.

Alternatively you can check for it.

set -a -- "$OPENSHIFT_HOMEDIR/app-root/runtime/bin/"
case :${PATH:=$1}: in
(*:"$1":*) ;; (*)
    PATH=$1:$PATH
esac;  set +a --
Answered By: mikeserv
Categories: Answers Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.