path – Do Duplicate Entries in PATH Variable Revoke Precedence?

path

If I have a PATH variable that (when exploded onto multiple lines) contains something like this (with a few notes added by me):

/Users/brandon/.rvm/gems/ruby-2.0.0-p353/bin
/Users/brandon/.rvm/gems/ruby-2.0.0-p353@global/bin
/Users/brandon/.rvm/rubies/ruby-2.0.0-p353/bin
/opt/local/bin
/opt/local/sbin
/usr/local/sbin
/usr/local/bin   # <<--- notice this path appears again later
/usr/bin         # <<--- notice this comes AFTER /usr/local/bin
/bin
/usr/sbin
/sbin
/usr/local/bin   # <<--- here it is again!
/usr/local/git/bin
/Users/brandon/bin
/Users/brandon/.homebrew/bin
/usr/local/mysql/bin
/usr/local/share/npm/bin
/Applications/Postgres93.app/Contents/MacOS/bin
/Users/brandon/.rvm/bin

is it possible for the presence of the second /usr/local/bin/ to cause the /usr/bin to take precedence over /usr/local/bin? This seems crazy (to me: I've never heard of such a thing) but that's exactly the behavior I'm seeing. I've just installed PHP with Homebrew, and yet the system PHP (from /usr/bin) is taking precedence:

$ which php
/usr/bin/php

BUT, after manually altering the PATH (rather than digging through all the files sourced by my .zshrc to try to figure out why & where the duplication is coming from) to remove the second instance of /usr/local/bin, I find that /usr/local/bin is taking precedence over /usr/bin as I would have expected it to in the first place:

$ which php
/usr/local/bin/php

What would cause this? Is this normal?

Best Answer

hash -r (for bash) If you just installed a binary, the shell may not know about it immediately as it does maintain a cache (vs. scanning PATH for every command.)

The path is scanned in order, duplicates make absolutely no difference. However, dumber shells may scan the duplicate entry more than once -- if foo is there twice and bar isn't in foo, foo may get scanned twice.

Related Question