Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mac OS X Mojave - set environment variable permanently

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.

Update

In mac os Bigsur(11.2.3), the default terminal was zsh ( I did not check for other versions) and setting envs in ~/.zshenv as in

echo 'export PATH=$PATH:$PATH:~/Library/Android/sdk/build-tools/29.0/' >> ~/.zshenv

and running . ~/.zshenv helped me saving the envs permanently

like image 625
nantitv Avatar asked Apr 12 '19 09:04

nantitv


People also ask

How do I make environment variables permanently on Mac?

Set an Environment Variable — temporary or permanent Otherwise, you can have it permanently in Bash Shell Startup Script with “Export” command. And then close the terminal window and open another one to check out if the set variable has disappeared or not. Temporary Variable is gone now.

How do I permanently save a PATH on Mac?

Setting the PATH Variable Permanently To do this, you need to access the shells configuration or profile file and add the programs path to it. Depending on the macOS version youre running on your Mac, this can be done via either the bash shell or zsh (z shell).

How do I set environment PATH in Mac?

bash_profile file when you need to generate the PATH variable for a single user account. Use the /etc/paths. d/ directory or folder via the path_helper command tool to generate the PATH variable for all user accounts on the system. This method only works on OS X Leopard and higher macOS version.


1 Answers

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/LaunchAgents.

like image 59
Danijel Avatar answered Sep 21 '22 12:09

Danijel