Linux: Add & Set Environment Variables

Introduction: Understanding Environment Variables in Linux

Environment variables are powerful dynamic values that influence the behavior of processes and applications in your Linux system. Think of them as key-value pairs that provide essential configuration details to your shell, programs, and scripts. They dictate everything from where the system looks for executable commands (PATH) to locale settings, default editors, and custom application configurations.

Whether you’re setting up a development environment, configuring a new application, or simply customizing your terminal experience, knowing how to properly add and manage environment variables is a fundamental Linux skill.

This comprehensive guide will walk you through various methods to add an environment variable in Linux, covering both temporary settings for your current session and permanent configurations that persist across reboots and new terminal windows.


Why Add Environment Variables? Common Use Cases

Before diving into “how,” let’s quickly understand “why” you’d want to add an environment variable:


Methods to Add an Environment Variable in Linux

There are several ways to add environment variables, depending on whether you need them temporarily for the current session or permanently across sessions and reboots.

Method 1: Temporarily Adding Variables with the export Command (Current Session Only)

The export command is the most common and immediate way to set an environment variable for your current shell session and any child processes spawned from it. This change is not permanent; the variable will be gone when you close the terminal session.

Syntax:

export VARIABLE_NAME="value"

Practical Example: Let’s add a temporary variable named MY_APP_DIR:

export MY_APP_DIR="/opt/my_application"

How to Verify Addition: To confirm that the variable has been successfully added, use the echo command:

echo $MY_APP_DIR

If successful, this command will output the value you assigned: /opt/my_application.

Using Variables Immediately: Once exported, you can use the variable in commands:

cd $MY_APP_DIR
ls $MY_APP_DIR/config

Adding to Existing Variables (e.g., PATH): A common use case is adding a new directory to your existing PATH variable so commands in that directory become discoverable:

export PATH="$PATH:/usr/local/custom_scripts"

Here, $PATH expands to its current value, and then :/usr/local/custom_scripts is appended.


Method 2: Permanently Adding Variables (User-Specific) via Shell Configuration Files

To make an environment variable persist across new terminal sessions and reboots for a specific user, you need to add it to your shell’s configuration files. For Bash users (the most common default shell), these are typically:

Steps to Permanently Add a User-Specific Variable:

  1. Open the appropriate configuration file in a text editor. For most interactive terminal sessions, ~/.bashrc is your go-to.

    nano ~/.bashrc
    

    (Tip: If you’re unsure which file is best, starting with ~/.bashrc is usually safe. If your variable isn’t loading, try ~/.profile.)

  2. Add the export command for your variable at the end of the file. It’s good practice to add a comment explaining its purpose.

    # Custom variable for my application
    export MY_API_KEY="your_secure_api_key_here"
    
    # Add a custom script directory to PATH
    export PATH="$PATH:$HOME/bin/my_scripts"
    
  3. Save the file and exit the editor. In nano, press Ctrl+O to save and Ctrl+X to exit.

  4. Apply the changes immediately to your current shell session by “sourcing” the file. This reloads the configuration without needing to close and reopen your terminal.

    source ~/.bashrc
    

    Now, verify with echo $MY_API_KEY or echo $PATH. The variable will also be available in any new terminal windows you open.


Method 3: Permanently Adding Variables (System-Wide)

For variables that need to be available to all users and processes on the system, you’ll modify system-wide configuration files. These typically require sudo (root) privileges.

Steps to Permanently Add a System-Wide Variable:

  1. Choose the appropriate file:

    • For simple KEY=VALUE variables that all users need, **/etc/environment** is often the cleanest.
    • For variables that require shell logic (e.g., appending to PATH dynamically for all users based on some condition) or for installing application-specific environment settings, create a new script in **/etc/profile.d/**.
  2. Open the file with sudo:

    sudo nano /etc/environment
    

    Or, to create a new script in profile.d (e.g., for Python):

    sudo nano /etc/profile.d/python_vars.sh
    
  3. Add your variable definition:

    • For /etc/environment:

      MY_GLOBAL_VAR="system_value"
      ANOTHER_APP_PATH="/usr/local/my_app/bin"
      

      (Important: No export command here!)

    • For /etc/profile.d/python_vars.sh (or /etc/profile):

      # Set Python 3.9 as default for all users
      export PYTHON_HOME="/opt/python-3.9"
      export PATH="$PYTHON_HOME/bin:$PATH"
      
  4. Save the file and exit the editor.

  5. Apply the changes:

    • For changes in /etc/environment, you typically need to reboot the system or log out and back in for all users to see the changes. Sourcing doesn’t usually work for this file in the same way as bashrc.
    • For changes in /etc/profile.d/ or /etc/profile, new login sessions will pick them up. You can force it for your current session by running source /etc/profile (though a full re-login is more reliable for system-wide effects).

Method 4: Setting Variables for a Single Command

Sometimes, you only need an environment variable to exist for the duration of a single command’s execution. You can do this by prefixing the command with the variable assignment. The variable will not be set in your current shell session.

Syntax:

VARIABLE_NAME="value" command_to_run arguments

Practical Example: Run a script with a DEBUG variable enabled, but only for that specific run:

DEBUG_MODE="true" python my_script.py --verbose

In this case, DEBUG_MODE is only visible to my_script.py and is not set in your shell environment.


How to Verify Your Environment Variables

Regardless of the method you use, it’s crucial to verify that your environment variables are set correctly.


Best Practices for Managing Environment Variables


Conclusion

Adding environment variables in Linux is a flexible process with options for temporary, user-specific permanent, and system-wide permanent configurations. By mastering the export command and understanding the role of shell configuration files like ~/.bashrc and /etc/environment, you gain precise control over your Linux environment. This fundamental skill empowers you to customize your system, streamline your workflows, and ensure your applications run exactly as intended.

Ready to Level Up Your Linux Skills? Continue exploring shell scripting, system administration, and advanced configuration techniques to unlock the full power of your Linux system!


Further Reading & Resources

Latest blog posts

Explore the world of programming and cybersecurity through our curated collection of blog posts. From cutting-edge coding trends to the latest cyber threats and defense strategies, we've got you covered.