How to set environment variables in the Bash Shell

October 4, 2023 / How-to Guide

Environment variables are dynamic values that affect processes and programs in Linux. This guide shows you how to view, set, and manage environment variables in Bash.

Follow the guide:

View Current Environment Variables

  1. To display all environment variables:
    Printenv
  2. To view a specific variable:
    echo $PATH
  3. To list all variables (including shell variables):
    Set

Set Temporary Environment Variables

  1. These variables exist only for the current session:
    export VARIABLE_NAME="value"
  2. Example:
    export MY_VAR="Hello World"
    echo $MY_VAR
  3. To add a directory to PATH temporarily:
    export PATH=$PATH:/new/directory

Set Permanent Environment Variables

  1. For Current User Only
    1. Edit ~/.bashrc (or ~/.bash_profile on some systems):
      nano ~/.bashrc
    2. Add at the end of the file:
      export VARIABLE_NAME="value"
      export PATH=$PATH:/new/directory
    3. Save and apply changes:
      source ~/.bashrc
  2. For All Users (Requires Root)
    1. Edit /etc/environment:
      sudo nano /etc/environment
    2. Add variables in this format (no export needed):
      VARIABLE_NAME="value"

Unset Environment Variables

  1. To remove a variable from the current session:
    unset VARIABLE_NAME
  2. Example:
    unset MY_VAR

Verify Your Changes

  1. After setting a variable, verify it:
    echo $VARIABLE_NAME
  2. Or check if it appears in the environment:
    printenv | grep VARIABLE_NAME

Important Notes

  • No spaces around the = sign when setting variables.
  • Always use $ to reference a variable’s value.
  • Use quotes for values containing spaces.
  • Changes to .bashrc require a new terminal session or source command.
  • System-wide changes may require a logout/login.
Customising Linux environments and automating server tasks?
A Linux VPS Hosting solution gives you full control over environment variables, application settings and server configurations for greater flexibility and efficiency.

That is it! Hope you liked our article. If you encounter any issues, feel free to contact our support staff.

Spread the love