Homebrew PATH set in .zshenv is overridden

Solution 1:

After ~/.zshenv is sourced, the next file that is loaded is /etc/zprofile, which is provided by macOS. This script executes

eval `/usr/libexec/path_helper -s`

The manual for path_helper explains:

The path_helper utility reads the contents of the files in the directories /etc/paths.d and /etc/manpaths.d and appends their contents to the PATH and MANPATH environment variables respectively.

...

Prior to reading these directories, default PATH and MANPATH values are obtained from the files /etc/paths and /etc/manpaths respectively.

In my opinion it is unclear from the description, but path_helper appears to rebuild PATH in the following order:

  1. Directories listed in the file /etc/paths
  2. Directories listed in the files in /etc/paths.d (note: files are not enumerated in sorted order)
  3. Any other directories that were previously in the PATH variable, excluding those that appear in the above lists

Therefore, path_helper ends up moving Homebrew to the end of PATH.

The solution is to do path initialization in ~/.zprofile on macOS. This file is loaded after /etc/zprofile and before ~/.zshrc.