Linux: Add & Set Environment Variables

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

  • Defining Paths: Extending the PATH variable so your system can find custom scripts or executables without specifying their full path.
  • Application Configuration: Setting variables that applications read for their behavior (e.g., JAVA_HOME, M2_HOME for Java/Maven).
  • API Keys/Credentials: Storing non-sensitive API keys or tokens for quick access within scripts (though for sensitive data, secure vaults are recommended).
  • Custom Settings: Personalizing your shell (e.g., PS1 for prompt customization) or defining aliases.
  • Development Workflows: Specifying build directories, database connections, or debugging flags for specific projects.

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"
  • VARIABLE_NAME: The name of your variable (conventionally uppercase).
  • "value": The string or path you are assigning to the variable. Quotes are important if the value contains spaces or special characters.

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:

  • ~/.bashrc: Executed for interactive non-login shells (e.g., opening a new terminal window). This is generally the most recommended place for user-specific variables that don’t need to be set for non-interactive scripts.
  • ~/.bash_profile or ~/.profile: Executed for login shells (e.g., logging in via TTY, SSH, or some desktop environments). ~/.profile is more general and often sourced by different shells, while ~/.bash_profile is Bash-specific. Many users put source ~/.bashrc inside their ~/.bash_profile to ensure bashrc settings load for login shells too.

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.

  • /etc/environment: This file is specifically designed for simple, system-wide environment variable definitions. It uses a simple KEY=VALUE syntax and does not support shell syntax (like export or $ for expansion). Variables set here are typically available very early in the system startup process.
  • /etc/profile: This is a system-wide script executed for login shells by all users. It often sources other scripts from /etc/profile.d/.
  • /etc/profile.d/*.sh: This directory contains scripts that are automatically executed by /etc/profile. Many installed applications (like Java or Go) place their environment setup scripts here. This is a good place for more complex system-wide variable setups that require shell logic.

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.

  • echo $VARIABLE_NAME: As shown above, this is the quickest way to check a specific variable’s value.
  • env or printenv: These commands list all currently set environment variables in your session.
    env | grep MY_API_KEY
  • set: This command lists all shell variables, environment variables, and functions. It provides a more comprehensive view of your current shell’s state.

Best Practices for Managing Environment Variables

  • Be Specific: Only set variables where they are truly needed (e.g., user-specific vs. system-wide).
  • Use Descriptive Names: Choose clear, all-caps names for your variables (e.g., APP_CONFIG_PATH).
  • Comment Your Files: Add comments in your .bashrc or other config files to explain why a variable is set.
  • Back Up Files: Always back up configuration files (e.g., cp ~/.bashrc ~/.bashrc.bak) before making changes.
  • Avoid Sensitive Data: Do not store highly sensitive information (passwords, private keys) directly in plain text environment variables, especially in system-wide files. Use more secure methods like environment variable managers (e.g., direnv), vault services, or application-specific configuration.
  • Order Matters: Be mindful of the order of commands in your configuration files, especially when modifying PATH or similar 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

Linux