DEV Community

Cover image for Environment variables in Linux and Mac OS

Posted on

Environment variables in Linux and Mac OS

If you have worked on a project which consists of API’s or anything that involves tokens to interact with servers, you might have worked with environment variables. This article explains how to create environment variables in MAC and Linux OS. They can also stop disasters such as these happening.

What are the Environment variables, and why use them?
Environment variables are system variables with a specific meaning that can be referenced when necessary all over the Operating System. They usually begin with a $ symbol in bash. It must also be noted that when storing API keys or secret data for Production, environment variables are not the best option. They are handy for testing and development as most languages have inbuilt support.

Create the variables.

Place your keys in the following format in ~/.bashrc in case of Linux and ~/.bash_profile in case of Mac OS.

export SECRETKEYNAME="Some-Key-here"

Note: The variable name should be in uppercase letters only.

Once you are done copying your key to the file, the next step is to refresh the files and make the variables accessible all over the system. You can do it using the command source ~/.bashrc Linux or source ~/.bash_profile in case of Mac OS. You can use printenv to view all the variables on Mac and Linux OS. You can also access the existing variables like $HOME or $USER using the terminal.

Example: echo $HOME displays your home directory name.

To set the environment variables across sessions and restarts, you can store them in ~/.bashrc , ~/.bash_profile or ~/.profile.

The practice of using environment variables is an excellent way to avoid sensitive information leaks and keys, especially while working with open source projects and public repositories.

References and further reading:

  1. Quora Thread on AWS Hack and 50K Bill.
  2. Environment variables on Wikipedia
  3. How to manage environment variables in local development
  4. An Extensive Read on Digital Ocean

Top comments (0)