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 Mac OS X. Speaking of Mac 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.
Before getting started, you might want to see the existing $PATH just in case you mess something up, that way you can easily restore to it by exporting using the same commands. To check the current $PATH simply type: “echo $PATH”
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:
How to Add 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 many versions of Mac OS X, but zsh is the default in later modern releases, and of course there are other shells like sh, ksh, and tcsh are also bundled with the Mac. Changing the Mac OS X shell is a very easy process either with chsh, or within Terminal and/or iTerm2 preferences.