Skip to main content

To set an environment variable on Ubuntu, can be achieved via a few options.  This depends on whether you want the variable to be system-wide or specific to a user's session.  Here are a couple of more common methods for setting environment variables:

Setting environment variables for the current session

You can set an environment variable for the current user's session by using the export command in your shell. The variable will be available as long as the session is active.

To set an environment variable for the current user session:

export VARIABLE_NAME="var_value"

For example:

export OPENAI_API_KEY="16deab4826...ef137cde1abc779"

This variable will be available in the current terminal session. If you open a new terminal or log out and log back in, the variable will not be set. To make it persistent, you can add the export command to your shell's configuration file, such as ~/.bashrc, ~/.bash_profile, or ~/.zshrc, depending on your shell.

 

Setting environment variables system-wide

To set an environment variable system-wide (available to all users), you can use one of the following methods:

In /etc/environment (System-Wide Environment File): Edit the /etc/environment file and add a line with the variable assignment. This file contains system-wide environment variable definitions.

sudo nano /etc/environment

Add a line like we did above

VARIABLE_NAME="var_value"

Or swap it out to the values noted above

OPENAI_API_KEY="16deab4826...ef137cde1abc779"

Save and exit the editor. The variable will be available to all users after a system reboot.
In a Shell Script (Startup Script): Create a shell script (e.g., in /etc/profile.d/) with the variable assignment and make it executable.
For example, create a new file in /etc/profile.d/myenv.sh and add:

#!/bin/bash
export VARIABLE_NAME="variable_value"

Make the script executable:

sudo chmod +x /etc/profile.d/myenv.sh

The variable will be available system-wide after a system reboot or user login.
After setting an environment variable system-wide, it will be available to all users and persist across system restarts.

To make environment variable changes take effect without rebooting, you can run the following command in your current terminal session:

source /etc/environment

Related articles