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


Or swap it out to the values noted above


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/ and add:

export VARIABLE_NAME="variable_value"

Make the script executable:

sudo chmod +x /etc/profile.d/

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

Andrew Fletcher06 May 2024
Exploring historical memory usage monitoring with Sysstat
In the realm of system administration and monitoring, understanding memory usage trends is crucial for maintaining system health and performance. While tools like htop offer real-time insights into memory usage, they lack the capability to provide historical data. So, what if you need to analyze...
Andrew Fletcher01 May 2024
Common commands used in Ubuntu - in progress
A growing list of commands I've used and what they do in no specific ordersudo snap install bw ps aux | grep java whoami ip addr show uptime sudo apt update && sudo apt upgrade -y cat /etc/os-release sudo apt-get install needrestart sudo reboot sudo needrestart sudo ckan sysadmin...