Categories
Mac Mac setup Tech

Really, really add /usr/local/bin to the PATH variable on macOS

In newer macOS versions custom executables belong in the directory /usr/local/bin. However, the path /usr/local/ is not included in the system’s default PATH variable. I show you how to really, really add /usr/local/bin to the system PATH variable.

Since macOS El Capitan you cannot put any custom files under /usr/bin/. Even when you sudo as hard as you can (with administrator rights) you cannot touch the files in that directory. Therefore, you are forced to use /usr/local/bin for your custom executables. Also if you are using Homebrew to install programmes on your system, the programme executables will be installed under the path /usr/local/bin. However, the path /usr/local/ is not included in the system’s default PATH variable so you cannot e.g. use these executables from within your Java programmes. You most-probably want to add the path /usr/local/bin to the PATH environment variable to add the executables to your default executables.

Of course, you can easily add /usr/local/bin to the PATH environment variable by editing the file ~/.profile and add the expression:

export PATH=/usr/local/bin:$PATH

But does this really add the executables under the path /usr/local/bin to the default executables? The answer is no, it does not. For example, consider you are running a Java application that executes some system executables/programmes myex located in /usr/local/bin using the Runtime object:

Runtime.getRuntime().exec("myex")

The code above would result in an error because the default path configuration does not include /usr/local/bin. The default path configuration is usually something like /usr/bin:/bin:/usr/sbin:/sbin.

One workaround may be to change the Java code and explicitly source the .profile file containing the aforementioned export statement:

Runtime.getRuntime().exec("source ~/.profile; myex")

Another workaround may be to call the executable using its absolute path /usr/local/bin/myex:

Runtime.getRuntime().exec("/usr/local/bin/myex")

Both workarounds would make strong assumptions either about the contents of the profile configuration or about the location of the executable. The elegant solution is to add the executable myex to the default executable path. This comment on github provides a way to achieve that. Open a Terminal window and copy & paste the following command:

sudo launchctl config user path /usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin

The command will set the default environment and add /usr/local/bin to the PATH variable of the system’s default environment. Hence, the executables under /usr/local/bin are callable from the default configuration.

Leave a Reply