Duplicate entries in $PATH a problem?

Having more entries in $PATH doesn't directly slow your startup, but it does slow each time you first run a particular command in a shell session (not every time you run the command, because bash maintains a cache). The slowdown is rarely perceptible unless you have a particularly slow filesystem (e.g. NFS, Samba or other network filesystem, or on Cygwin).

Duplicate entries are also a little annoying when you review your $PATH visually, you have to wade through more cruft.

It's easy enough to avoid adding duplicate entries.

case ":$PATH:" in
  *":$new_entry:"*) :;; # already there
  *) PATH="$new_entry:$PATH";; # or PATH="$PATH:$new_entry"
esac

Side note: sourcing someone else's shell script means executing code that he's written. In other words, you're giving your friends access to your account whenever they want.

Side note: .bashrc is not the right place to set $PATH or any other environment variable. Environment variables should be set in ~/.profile. See Which setup files should be used for setting up environment variables with bash?, Difference between .bashrc and .bash_profile.


I've seen people clean up duplicates from their PATH variable using awk and something like this:

PATH=$(printf "%s" "$PATH" | awk -v RS=':' '!a[$1]++ { if (NR > 1) printf RS; printf $1 }')

You could try adding that to your own bashrc and make sure you source the other files somewhere before running that.

An alternative would be to use the pathmerge utility.

As for your speed problem, this will not affect the startup time of the shell in any significant way but it may save some time doing tab completion for commands, especially when the command is not found in the path and it does repeated searches through the same folders looking for it.

A note on security: You should really heed Gilles' warnings about security here. By sourcing a file owned by another user you are giving a free pass to those users to execute their own code as your user every time you start a shell. If you don't trust those users with your password, you shouldn't be sourcing their shell files.


Based on @Gilles answer you may wrap it in a function to minimize typing:

function addToPATH {
  case ":$PATH:" in
    *":$1:"*) :;; # already there
    *) PATH="$1:$PATH";; # or PATH="$PATH:$1"
  esac
}

addToPATH /Applications/AIRSDK_Compiler/bin
addToPATH ~/.local/lib/npm/bin

Tags:

Bash

Path