When developing software, it’s good practice to put anything you don’t wish to be public, as well as anything that’s “production-environment-dependent” into environment variables. These stay with the local machine. This is especially true if you are ever publishing your code to public repositories like Github or Dockerhub.

Good candidates for environment variables are things like database connections, paths to files, etc. Hosting platforms like Azure and AWS also let you easily set the value of variables on production and testing instances.

I switch back and forth between Windows, OSX and even Linux during development. So I wanted a quick cheatsheet on how to do this.

Writing Variables

Mac OSX (zsh)

The default shell for OSX is now zshell, not bash. If you’re still using bash, consider upgrading, and consider using the great utility “Oh My Zsh.”

will print out environment variables

To save new environment variables:

export BASEBALL_TEAM=Seattle Mariners

To save these permanently, you’ll want to save these values to:

~/.zshenv

So, in terminal you’d bring up the editor:

and add export BASEBALL_TEAM=Seattle Mariners to this file. Be sure to restart a new terminal instance for this to take effect, because ~./zshenv is only read when a new shell instance is created.

bash shell (Linux, older Macs, and even Windows for some users)

export BASEBALL_TEAM=Seattle Mariners
​
echo $BASEBALL_TEAM
Seattle Mariners 
​
printenv 
< prints all environment variables > 
​
// permanent setting
sudo nano ~/.bashrc
// place the export BASEBALL_TEAM=Seattle Mariners in this file
// restart a new bash shell 

Windows

  • Right click the Windows icon and select System
  • In the settings window, under related settings, click Advanced System Settings
  • On the Advanced tab, click Environment variables
  • Click New to create a new variable and click OK

Dockerfile

ENV [variable-name]=[default-value]
​ 
ENV BASEBALL_TEAM=Seattle Mariners

Reading Variables

Python

import os
​
print(os.environ.get("BASEBALL_TEAM"))

Typescript / Javascript / Node

const db: string = process.env.BASEBALL_TEAM ?? ''

C#

var bestBaseballTeam = Environment.GetEnvironmentVariable("BASEBALL_TEAM");

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.