Setting environment variables is a foundational task of any Linux system. They are dynamic values that provide information and configuration options for running processes and applications. In this guide, we’ll explore the different methods and best practices for setting environment variables in a Linux environment.

Method 1: Using the export Command

The most straightforward way to set an environment variable in Linux is by using the export command. This method is suitable for setting variables temporarily, which will be available only for the current session.

  • Open your terminal.
  • To create a new environment variable, use the following syntax:
export VARIABLE_NAME="variable_value"

ReplaceVARIABLE_NAME with the name you want to give to your environment variable and variable_value with the desired value.

  • To verify that your variable has been set, you can echo it:
echo $VARIABLE_NAME

Method 2: Modifying the .bashrc, .bash_profile or .zshrc File

To make environment variables persist across sessions, you can add them to your user’s profile file. Depending on your distribution, this file could be .bashrc, .bash_profile or .zshrc Here’s how to do it:

  • Open your terminal.
  • Use a text editor like nano or vim to edit your profile file:
vim ~/.bashrc

or

vim ~/.bashrc

or

vim ~/.zshrc
  • Add the following line at the end of the file:
export VARIABLE_NAME="variable_value"

Again, replaceVARIABLE_NAME with your desired variable name and variable_value with the value you want.

  • Save and exit the text editor.
  • To make the changes take effect in the current session, run:
source ~/.bashrc

or

source ~/.bash_profile

or

source ~/.zshrc

Method 3: Using the /etc/environment File

System-wide environment variables can be set in the /etc/environment file. These variables are available to all users on the system.

  • Open your terminal with superuser privileges (use sudo).
  • Edit the /etc/environment file with a text editor:
sudo vim /etc/environment
  • Add your environment variables in the following format:
VARIABLE_NAME="variable_value"
  1. Save and exit the text editor.
  2. To apply the changes, you may need to log out and log back in, or restart your system.

Method 4: Using the export Command in a Shell Script

Another way to set environment variables is by creating a shell script that sets them.

  • Create a new shell script with your favorite text editor:
vim setenv.sh
  • Add the export commands for your variables:

#!/bin/bash
export VARIABLE1="value1"
export VARIABLE2="value2"

Save and exit the text editor.

  • Make the script executable:
chmod +x setenv.sh
  • Run the script:
./setenv.sh

These are the primary methods for setting environment variables in Linux. Whether you need to configure your system or customize software, environment variables are a powerful tool to help you manage your Linux environment effectively.

Got any queries or feedback? Feel free to drop a comment below!

Categorized in: