4 Options to Create Environment Variables on *nix Machines

4 Options to Create Environment Variables on *nix Machines

Setting ENVs on macOS and other *nix Systems

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 EXPORT command. 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_VAR created in one session that is not available in another. env_export_example.png

  • Using a .env file 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. env-file-example.png

  • Create permanent environment variables by modifying your Bash or ZSH (Z) Shell Profiles. Based on whatever terminal you use, open the following (macOS) ~/.bash-profile (bash) or ~/.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. create_env.png

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

End

These are helpful reminders when setting up and accessing environment variables for development.