Posted on 2024-09-23 by Ehab Younes
Last modified on 2024-09-24
Tagged as: Environment VariablesWindowsLinux

Setting Environment Variables

Environment variables are key-value pairs used by operating systems to define the environment in which programs run. Below are step-by-step instructions for setting environment variables on both Windows and Linux.

Windows

Temporary Environment Variable

  1. Open Command Prompt or PowerShell.

  2. Run the following command to set a variable temporarily:

    set VARIABLE_NAME=value
    

    Example:

    set PATH=C:\MyFolder;%PATH%
    

Note: This variable will only last for the current session. When you close the window, the environment variable will be lost.

Persistent Environment Variable

Using the GUI (Graphical User Interface)

  1. Press Win + X and select System (or go to Control Panel > System).
  2. Click on Advanced system settings on the left side.
  3. In the System Properties window, click on Environment Variables.
  4. In the User variables or System variables section:
    • Click New to add a new variable.
    • Click Edit to modify an existing variable.
    • Click Delete to remove a variable.
  5. Enter the variable name and value, then click OK.

Note: User variables apply only to the current user, while system variables apply to all users on the machine.

Using the Command Line

  1. Open Command Prompt or PowerShell with administrator rights.

  2. Run the following command to set a persistent environment variable:

    setx VARIABLE_NAME "value"
    

    Example:

    setx PATH "C:\MyFolder;%PATH%"
    

Note: Persistent environment variables set via setx will apply in new Command Prompt/PowerShell windows but not in the current one.


Linux

Temporary Environment Variable

  1. Open a terminal window.

  2. Set an environment variable temporarily by typing:

    export VARIABLE_NAME=value
    

    Example:

    export PATH=/usr/local/myfolder:$PATH
    

Note: This will only last for the current terminal session. The variable will disappear when the terminal is closed.

Persistent Environment Variable

  1. Open a terminal and use a text editor to open your shell configuration file (.bashrc, .zshrc, etc. depending on your shell):

    nano ~/.bashrc
    

    or

    nano ~/.zshrc
    
  2. Add the export command at the end of the file:

    export VARIABLE_NAME=value
    

    Example:

    export PATH=/usr/local/myfolder:$PATH
    
  3. Save the file and exit the editor.

  4. Apply the changes by running:

    source ~/.bashrc
    

    or

    source ~/.zshrc
    

Note: This will make the environment variable persistent across terminal sessions.