Linux and UNIX, as opposed to Windows, we are more likely to have experience with environment variables. Here we will discuss how to set environment variables in Linux using the bash shell.

List all environment variables

Console - user@hostname ~ $

1
set

Output

1
2
3
4
BASH=/bin/bash
.
.
.

Print a specific environment variable

Console - user@hostname ~ $

1
echo $HOME

Output

1
/home/user

Setting environment variables

The format for setting an environment variable in the bash shell is KEY=value with no spaces around the equal sign. In addition, when putting it in a configuration file it is necessary to prepend it with export. The following is an example of how to set an environment variable in one of the configuration files, it also works on the command line; we will set the variable EC2_HOME to /opt/aws/ec2-api-tools:

Console - user@hostname ~ $

1
export EC2_HOME=/opt/aws/ec2-api-tools

Global environment variables

/etc/profile

This is read once at login. Use /etc/profile.d instead if you can.

/etc/bashrc

This is read every time we start a new bash shell

/etc/profile.d

Put a file that has .sh at the end, and /etc/profile will run it. This allows for a more modular setup, and keeps /etc/profile from getting cluttered.

/etc/profile.d/ec2-api-tools.sh

1
2
export EC2_HOME=/opt/aws/ec2-api-tools
export PATH=$PATH:$EC2_HOME/bin

User specific variables

~/.bash_profile

This is run once at login. Most things should be put in ~/.bashrc, but if we only want it run once, this is the place. For example, if our distro does not have ssh-agent set up for you, this would be a good place to put it, since you only want one running and then have it shared amongst all the shells you start.

~/.bashrc

This is run every time we create a new bash shell. Most of your user specific variables should be put in here.