What is an Environment Variable?
An environmental variable is a dynamic object containing an editable value, which can be used by one or more programs. Environmental variables help programs know what directory to install files, where to store temporary files or where to find user profile setting. They help shape the environment the programs use to run.
How to set an environment variable?
There are 2 ways to set an environment variables: temporarily and permanently. A
Temporary Environment Variable
temporary environment variable is only accessible during the current session of the terminal. Once the session is closed the environment variable is removed.
The general syntax is:
export Variable_Name = Variable_Value
For example:
export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk-16.jdk/Contents/Home"
Permanent Environment Variable
For permanent setting, we need understand where to put the “export” script. In this practice, the script is added to the bash profile under the home directory. We can open and edit the “~/.bash_profile” like:
nano ~/.bash_profile
vim ~/.bash_profile
vi ~/.bash_profile
For example, we can create a test directory to the PATH environment variable by adding a line of script like this:
export PATH=/usr/test/directory:$PATH
Don’t forget to execute the file content using the source command.
source ~/.bash_profile
Finally, check the environment variable list for PATH and you’ll see the PATH variable now holds the new value.
Remove the permanent variable
Delete the line of export script from the bash profile, execute it, close and reopen the terminal and there you go, the environment variable is removed successfully.