Environment variables are used to store system-wide values that can be used by any user and process under the operating system. Setting environment variables is essential in the steps of certain installations we covered such as How To Install Java or How To Install Java On Raspberry Pi.
This tutorial explains how to view, add, and remove temporary and permanent environment variables on macOS.
- A system running the latest version of macOS
- Access to the terminal
- A user with admin-level privileges
Check Current Environment Variables
There are two ways to check current environment variables in macOS:
1. Display and review a list of all current environment variables.
2. Display and review a specific environment variable.
List All Environment Variables
printenv command to display a list of currently set environment variables:
Note: If you want to display the complete list of shell variables, use the
Check A Specific Environment Variable
If you want to display the value of any specific environment variable, use the
echo $[variable name]
For example, to check the value of the
PATH variable which stores a list of directories with executable files, use the
Note: Always use the
$ prefix when specifying a variable name.
Set Temporary Environment Variable
The value you assign to a temporary environment variable only lasts until you close the terminal session. This is useful for variables you need to use for one session only or to avoid typing the same value multiple times.
Assign a temporary environment variable with the
[variable_name]: The name for the new temporary environment variable you want to set.
[variable_value]: The value you want to assign to the new variable.
export command also allows you to add new values to existing environment variables:
[existing_variable_name]: The name of the environment variable you want to add a new value to.
[new_variable_value]: The value you want to add to an existing variable.
For example, if you want to add a custom folder path to the
PATH variable, use:
Set Permanent Environment Variable
Permanent environment variables are added to the
1. Find the path to
.bash_profile by using:
2. Open the
.bash_profile file with a text editor of your choice.
3. Scroll down to the end of the
4. Use the
export command to add new environment variables:
5. Save any changes you made to the
6. Execute the new
.bash_profile by either restarting the terminal window or using:
Note: Learn the fundamental difference between .bashrc and .bash_profile in our article bashrc vs. bash_profile: What Is the Difference?.
Unset Environment Variable
unset command to remove an environment variable:
After following this tutorial, you should know how to set temporary and permanent environment variables in macOS. This should make it easier for you to configure software packages in the future.