Avoid duplicates in $PATH

By: | Comments: No Comments

Posted in categories: Computer Tips, Work related

Linux search /etc/profile.d and ~/.bashrc, ~/.bash_profile for system and user defined environmental variables. One of the most manipulated variable is $PATH. You can see this by running

$ echo $PATH

In most cases, when a new 3rd party software is installed, and you want it to be in your default executable search path, you insert a line like

export PATH=$PATH:/where/your/new_executables

in your ~/.bash_profile or in a file in /etc/profile.d if you are a system administrator. This appends a new search path onto the existing one.

However, if you launch another terminal, a shell, etc., all these scripts are loaded again and you got duplicated entries in $PATH.

This looks harmless and does not affect system performance in most cases since bash looks for the first available executable in the search path and ignore all later appended paths.

However, if you are running some scripts that loop into multiple layers of shells, this could cause the $PATH string overflow and disrupt your script. Also for cosmetic reason, a very long $PATH filled with duplicates are ugly.

To not generate duplicates, we can do:

NEWPATH=/where/your/new_executables 
if [ -d "$NEWPATH" ] && [[ ":$PATH:" != *":$NEWPATH:"* ]]; then
    PATH="${PATH:+"$PATH:"}$NEWPATH"
fi
export PATH;

for appending or

NEWPATH=/where/your/new_executables 
if [ -d "$NEWPATH" ] && [[ ":$PATH:" != *":$NEWPATH:"* ]]; then
    PATH="$NEWPATH${PATH:+":$PATH"}"
fi
export PATH;

for prepending, instead of the

export PATH=$PATH:/where/your/new_executables

way. This, will prevent generating duplicated entries in $PATH since it will only add in a new entry when the new entry is not found in the existing environmental variable.

Be the first to comment!

Leave a Reply