Priority setting of $PATH in macOS

Image for post
Image for post

In most OSs, usually different versions of the same software can exist at the same time, and they usually exist in different locations.

For example (macOS):

Image for post
Image for post

There are multiple lines here, the first line is the highest priority, which is the version currently in use, and the second line is the version that comes with the system.
Therefore, if you want to use the version of the following line, just move the second line to the top, what should you do?

In fact, in Windows 10, this is very simple:

Image for post
Image for post

Use Move Up and Move Down to move the selected path up and down to change the priority. However, in macOS, there is no such window.
Here, we will discuss the $PATH in macOS.

The level of environment variables in macOS is divided into system level and user level. As you can see from the name, their scope of action is different. System level variables are valid for all users, while user level variables are only valid for specific users.

The user-level $PATH is stored in the /etc/paths file. The variable seen from echo $PATH is the content of this file plus the content of the system-level path (newline character’/n’ becomes’:’, here is My $PATH is chestnut):

Image for post
Image for post

Lines 19 and 20 are system-level variables. As you can see, the user-level content is before the system level, and the OS starts from this big string Scanned, so user-level paths have higher priority than system-level paths.

Below is the content of my /etc/paths file (the paths that are exported to the PATH are written here):

Image for post
Image for post

This directly reflects the priority, /usr/local/opt/ruby/bin is on /usr/bin, so when I use which -a ruby, the previous result will appear. Now I lower the two lines, Then create a new tab in terminal.app, again which -a ruby, you will find this result:

Image for post
Image for post

So through this file, you can change the priority of environment variables at will, to achieve the effect of Windows.

For system-level variables, the location is in the /etc/paths.d directory. If you want to set it, you need to touch a file, write the variable to this file and save it, and move to this directory.

Train for gains

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store