In Linux, environment variables are key-value pairs that influence the behavior of processes and applications. These variables can store user-specific data, file paths, or application-specific configurations. Defining environment variables allows customization of how the shell and applications behave.

Environment variables can be defined temporarily for the current session or permanently across sessions. Temporary variables only exist in the terminal where they are defined. To make variables persistent, they need to be added to specific shell configuration files, such as .bashrc, .zshrc, or .profile. Each shell has its configuration file, and adding variables to the correct file ensures they are loaded each time the terminal starts.

Different shells use different configuration files. For Bash, the most common shell, .bashrc is used for interactive sessions and .profile for login shells. For Zsh, the .zshrc file is used. Knowing where to add these variables ensures they are applied to the appropriate shell environment.

Steps to define environment variables in Linux command line:

  1. Open a terminal application.
  2. Define a temporary environment variable using the export command.
    $ export VARIABLE_NAME=value

    This command creates a variable that will only last for the current terminal session. Replace VARIABLE_NAME and value with the desired variable name and value.

  3. Verify the variable is set by printing its value.
    $ echo $VARIABLE_NAME
  4. To set the environment variable permanently, edit the .bashrc file.
    $ nano ~/.bashrc

    If you are using a different shell, such as Zsh or need to define variables for login shells, edit .zshrc or .profile instead of .bashrc:

    1. For Zsh, use .zshrc
    2. For login shells, use .profile
  5. Add the export command to the end of the file.
    export VARIABLE_NAME=value

    After adding the variable to .bashrc, .zshrc, or .profile, it will persist across future terminal sessions. Choose the file based on the shell in use: .bashrc for Bash, .zshrc for Zsh, and .profile for login shells.

  6. Reload the .bashrc file to apply the changes without restarting the terminal.
    $ source ~/.bashrc
  7. Confirm that the variable is set correctly by printing its value.
    $ echo $VARIABLE_NAME 

    Environment variables defined in .bashrc, .zshrc, or .profile will persist across sessions, ensuring consistency every time the terminal is opened.

Discuss the article:

Comment anonymously. Login not required.