How to set environment variable in MacOS

Advertisements

Environment variables (env-vars) are used to save system-wide value and those values can be accessed later by the system itself, the user, processes or applications. Each Operative System has its own way to create environment variables, in this article we will see how to do it for MacOS.

View all the Environments Variables

In MacOS we can view all the environment variable values by using the command printenv

agamboa% printenv
PATH=/Users/agamboa/.nvm/versions/node/v12.8.0/bin:/usr/local/opt/postgresql@9.5/bin:/Users/agamboa/.jenv/shims:/usr/local/opt/gradle@6/bin:/usr/local/opt/awscli@1/bin:/usr/local/opt/awscli@1/bin:/usr/local/opt/openjdk@8/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/MacGPG2/bin
SHELL=/bin/zsh
TERM=xterm-256color
USER=agamboa
TMPDIR=/var/folders/7t/0bw1wkx14bb5tq783t7lx_gw0000gp/T/
COMMAND_MODE=unix2003
LOGIN_SHELL=1

View a specific Environment Variable

To view the value for a specific environment variable it’s possible with echo $<env-var name>

 % echo $PATH
/Users/agamboa/.nvm/versions/node/v12.8.0/bin:/usr/local/opt/postgresql@9.5/bin:/Users/agamboa/.jenv/shims:/usr/local/opt/gradle@6/bin:/usr/local/opt/awscli@1/bin:/usr/local/opt/awscli@1/bin:/usr/local/opt/openjdk@8/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/MacGPG2/bin

Set an Environment Variable

There are two ways to set an environment variable, temporarily and permanently. A temporary environment variable is one that is only accessible during the current session of the terminal, once the terminal is closed the env-var value will be removed. We can use the command export <EnvVarName>=<EnvVarValue> .

Advertisements
% export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk-16.jdk/Contents/Home" 

In order to set an environment variable permanently, without requiring to set it every time the terminal is opened. First it’s required to know what is the shell type in our MacOS, we have bash and zsh as possible types.

In case the shell type is bash , then, the env-vars should be added to the .bashrc or the .bash_profile files. In the case zsh is the shell type, then the file is .zshrc . So, let’s add the a new line in the corresponding file.

export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk-16.jdk/Contents/Home"  

Once the file is saved, we can close the terminal and open it again. From now on, the env-var will be set automatically. Another way without closing the terminal is to run. source <shell-file> .

% source ~/.zshrc


Conclusion

We have seen how to view and set up environment variables in MacOS, this should make it easier for you to configure software packages in the future.

Advertisements

Leave a Reply

Your email address will not be published. Required fields are marked *