macOS

Add /usr/local/bin to system PATH variable on macOS

  • dani

dani

2 min read

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. This article shows you how to add /usr/local/bin to the system PATH variable on macOS.

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. As a consequence, you most-probably want to add path /usr/local/bin to the system PATH environment variable to add the executables to your default executables.

Why not use the profile file?

Of course, you can easily add /usr/local/bin to the PATH environment variable by editing the profile file in ~/.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 because the default path configuration is usually something like /usr/bin:/bin:/usr/sbin:/sbin.

Changing the Java code

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.

Add /usr/local/bin to system PATH variable

As a result, the more 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.