16

Following this answer about best practices for configuring Zsh, I wanted to move my Homebrew PATH initialization to the ~/.zshenv file:

eval "$(/opt/homebrew/bin/brew shellenv)"

This modifies $PATH by placing the Homebrew directories first, so that tools installed with Homebrew take priority over system tools:

PATH=/opt/homebrew/bin:/opt/homebrew/sbin:/usr/bin:/bin

However, after the shell starts up, the Homebrew directories are last:

/usr/local/bin:/usr/bin:...:/opt/homebrew/bin:/opt/homebrew/sbin

1 Answer 1

19

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.

2
  • 8
    Basically Apple couldn't read the zsh documentation and put path_helper in the wrong place
    – mmmmmm
    Dec 9, 2021 at 17:12
  • 4
    Thank you for this, I discovered the same after putting many debug echo statements in every single /etc/z* and ~/.z* file like echo '/etc/zprofile sourced.' and discovered that macOS does things differently. Bummer. May 20, 2022 at 12:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .