How to Add a New Path to PATH at Command Line the Right Way
The user path is the series of directories that command line programs are searched in order to run. For example, if you type ‘iostat’ into the terminal, then iostat will be run from /usr/sbin because “/usr/sbin” is part of your $PATH. Accordingly, users who frequently use the command line may need to adjust or add new paths to their terminal so that commands can execute properly.
Perhaps obvious by now, modifying the PATH is aimed at more advanced users and developers who are using the Terminal and spending a lot of time at the command line. Average Mac users typically have no need to change, add, or otherwise adjust this in OS X. Speaking of OS X, while this is obviously Mac centric, you can use this same trick to add a PATH to your shell in Linux too, as well as most other unix flavors.
Adding a Directory to PATH
The easiest way to add a new path to $PATH (the environment variable) is with the export command. In this example we’ll add “~/opt/bin” to the user PATH with export:
You can run that directly from the command line, then check the $PATH with echo to show that it has been added like so:
This should return something like the following, note the newly added ~/opt/bin directory at the end:
Adding Multiple Paths to PATH
Just as multiple paths can be stored and strung together in $PATH in accordance to their search priority, you can also add new paths this way as well. We’ll use the same example as before, but this time also add the ~/dev/bin directory:
Setting PATH in Shell Profile
Keep in mind that for changes to PATH to persist, you’ll want to add them into ~/.profile, .zshrc, or ~/.bash_profile, depending on which shell you use. Use your favorite text editor to do that, whether it’s nano, emacs, or vim. If you’re getting complicated, it’s a good idea to add comments to the .profile to keep things easily scannable:
#Adding opt bin and dev bin to PATH for fun
Bash is the default shell in OS X, but zsh, sh, ksh, and tcsh are also bundled with the Mac, and changing the OS X shell is a very easy process either with chsh or within Terminal and/or iTerm2 preferences.