4 Options to Create Environment Variables on *nix Machines
Setting ENVs on macOS and other *nix Systems
2 min read
Setting Environment Variables
This article is meant as a reminder on how to set up and read environment variables for development.
Python Program Invocation. This option allows for variables to live for the duration of your program. This works when starting any Python program regardless of the operating system.
# Startup with env variables during program invocation SOME_KEY="qwerty123" SOME_PORT="99999" myPythonApp.py
Set via terminal with the
EXPORTcommand. Environment variables created in your terminal are saved to your terminals session. They only exist for the duration of your terminal window, once closed they are gone and are not available across multiple terminal windows. The screenshot below shows an example of a newly created environment variable
SOME_TEXT_VARcreated in one session that is not available in another.
.envfile in development project.
Add a dot env file to your project to store variables for your project. Depending on your project you can read in the environment variables in different ways specific to your project.
Create permanent environment variables by modifying your Bash or ZSH (Z) Shell Profiles. Based on whatever terminal you use, open the following (macOS)
~/.zshrc(ZSH) file in order to create permanent environment variables. You can open those files in nano, vi, or whatever text editor of your liking. The
#is a comment indicator. The example below is shown using the ZSH shell in my terminal.
Read Environment Variables
From your terminal, you can print out a single environment variable at a time or all of them at once.
echo $VAR_NAME # terminal print single variable
printenv # print all system environment variables
These are helpful reminders when setting up and accessing environment variables for development.