Setting Global Environment Variables on macOS
Unix-based systems load environment variables from three configuration files in a specific order.
The system first loads /etc/profile, which contains global envrionment variables applicable to all users. Next, it processes additional system configuration files such as /etc/bashrc. Finally, it loads user-specific configuration from ~/.bash_profile.
The first two files are system-wide configurations. Non-root users have read-only access to these files and require sudo privileges to modify them. The third file, ~/.bash_profile, is user-specific and recommended for custom environment settings. If this file doesn't exist in your home directory, create it using a text editor:
nano ~/.bash_profile
Adding a Global Variable to Your System
Consider a scenario where you installed PostgreSQL and need to add its binaries to your system's PATH for command-line access.
First, locate the bin directory of your PostgreSQL installation. For example:
/usr/local/Cellar/postgresql/15.2/bin
Edit your ~/.bash_profile file:
nano ~/.bash_profile
Within the file, locate the existing PATH definition. Multiple path entries must be separated by colons. Add your PostgreSQL bin directory to the PATH, ensuring it follows the same pattern:
export PATH="/usr/local/Cellar/postgresql/15.2/bin:${PATH}"
The ${PATH} reference at the end preserves existing system paths. Incorrect modification of this file can break essential shell commands like ls, rm, and cp.
Recovering from a Broken PATH
If misconfiguration renders shell commands unusable, restore basic functionality by running:
export PATH=/usr/bin:/usr/sbin:/bin:/sbin:/usr/X11R6/bin
This restores access to fundamental system utilities. The complete PATH contents are stored in /etc/paths. Without proper PATH configuration, binaries in /usr/bin, /usr/local/bin, and other directories become inaccessible, preventing direct execution of installed tools like Node.js, Python, or Ruby from the terminal.
Applying Changes
After saving ~/.bash_profile, the changes do not take effect immediately. While restarting your machine is one option, a more efficiant method uses the source command:
source ~/.bash_profile
This reloads the configuration file, making your custom environment variables available in the current session without requiring a system restart.