Mac OS X Mojave - set environment variable permanently

nantitv picture nantitv · Apr 12, 2019 · Viewed 9k times · Source

I am using mac os mojave (10.14.3). I set the environment variable in both ~/.bash_profile and ~/.bashrc and I ran both ~/.bash_profile and ~/.bashrc. Then in the same terminal I can see the values which I set (using printenv), but if I open a new terminal then I can not see previously set env variable.

Please give some suggestions.

Answer

Danijel picture Danijel · Sep 30, 2019

This works for OS X 10.14 "Mojave":

Step 1: go to your $HOME/Library/LaunchAgents directory and create setenv.MY_VAR.plist file with the following content:

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>setenv.MY_VAR</string> <key>ProgramArguments</key> <array> <string>/bin/launchctl</string> <string>setenv</string> <string>MY_VAR</string> <string>SOME_VALUE_FOR_MY_VAR</string> </array> <key>RunAtLoad</key> <true/> </dict> </plist>

Pay attantion that your file name and entries in the file match.

STEP 2: Run launchctl load ~/Library/LaunchAgents/setenv.MY_VAR.plist or - restart the system.

STEP 3: Restart your Terminal app.

STEP 4: Check if the var is there: env. It should give you: MY_VAR=SOME_VALUE_FOR_MY_VAR.

If you want to do more changes, first do launchctl unload... than launchctl load... again.

This is per user setting. If you want to set for all users, try doing the same in /Library/LaunchDaemons.