Adding directories to $PATH safely

$PATH is an environment variable containing a list of directories where executable programs are located in UNIX systems. The shell will search for executables in directories separated by the colon punctuation from left to right until it finds a match.

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

A typical scenario is to add ~/.local/bin as the first directory in $PATH, so you can comfortably install programs like Neovim, Tmux, and Python there.

$ PATH=$HOME/.local/bin:$PATH
$ echo $PATH
/home/jiholland/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

I usually add directories to $PATH in the ~/.bash_profile file, which is read by bash at login and will take effect each time you start a new terminal. The following function will only add directories to $PATH if it exists, is a directory, and is not already in $PATH.

$ cat ~/.bash_profile

pathadd() {
  if [ -d "$1" ] && [[ ":$PATH:" != *":$1:"* ]]; then
    PATH="$1:$PATH"
  fi
}

# Add these directories to PATH.
pathadd "$HOME/.local/bin"

unset -f pathadd

You can check out my dotfiles on GitHub if you found this useful.


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *