Setting environment variable through Mac terminal

Recently I ran into the problem of setting and unsetting environment variables under Mac terminal. We had a script which would access the credentials stored in the form of environment variables. It had been a while since I did something like this and it took me few minutes to understand what exactly I was supposed to do.

In this post I will demonstrate how to set/unset and use environment variables.

Adding environment variable

Environment variables are stored in the .bash_profile file stored in the root directory. Every time you want to add new environment variable, you will make changes to this file. Say, you want to add an environment variable for username, you can do it with following commands.

First edit the .bash_profile in the root directory

vi ~/.bash_profile

and add the following line to this file

export USERNAME="jayesh"

Where USERNAME is the key and jayesh is the value of this environment variable. Now bash usually requires you to restart the terminal to reflect the changes in bash_profile file. However, this can be eliminated by just typing following command. This command will update the system with new environment variable.

. ~/.bash_profile

Once this is done, you can view the list of all environment variables in the system by typing printenv on the terminal.

Accessing environment variables

Once you have this variable, you can access them in any shell script with following syntax,

ENV["USERNAME"]

This will produce the value of jayesh in the script.

Removing environment variable

Environment variable, once set they remain under system unless unset explicitly. As you will see if you remove the variables from .bash_profile, refresh the system and then run printenv, it will still show the removed environment variable. The solution is to remove them from bash_profile and unset them from command line.

First step is simple. Go to bash_profile file remove the line which sets the new variable and run . ~/.bash_profile on the command line.

Once this is done, run the following command in the terminal,

unset USERNAME

This will get completely rid of eliminated variable. Now, if you type printenv in the terminal you will see that variable is no longer in the list.