قالب وردپرس درنا توس
Home / Tips and Tricks / How to set environment variables in Bash on Linux

How to set environment variables in Bash on Linux

  A stylized Linux terminal with lines of green text on a laptop.
fatmawati achmad zaenuri / Shutterstock

There is more than one type of environment variable on Linux. Learn how to see them, create them for local and remote logins, and make sure they restart.

How Environment Variables Work

When you start a terminal window and the shell in it, a set of variables is referenced to ensure the shell is configured correctly. These variables also ensure that all information that the terminal window and shell may need to refer to is available. Collectively, these variables contain settings that define the environment you find in your terminal window, all the way to the command prompt appearance. So, of course, they are called environmental variables.

Some environment variables are system wide or global. Others are session-wide and can only be seen by you. Others cannot reference your session environment variables. A third set of environment variables is defined in the shell. Your locale, time zone and keyboard settings, the set of directories searched when the shell tries to find a command, and your default editor, are all stored in shell environment variables.

We're going to show you how to get the environment variables that exist on your system, and we'll describe how to make your own. We'll also show you how to make them available to underlying processes and keep using them during the reboot.

Environments and Inheritance

When a shell starts, it goes through an initialization phase. At this point, it reads the environment variables that define the shell's environment.

When a program or command is started from that shell ̵

1; known as a child process – it inherits the environment from the parent process – but beware! As we will see, you can create variables that are not added to your environment so that they are not inherited by a child process.

If the child process is a shell, that shell is initialized by itself. , fresh, set of variables. So, if you change the command prompt in the current shell and then start a child shell, the child shell will not inherit the changed command prompt from the parent.

Global Environment Variables

By convention, environment variables are capitalized. Here are some of the global environment variables and what the values ​​they contain represent:

  • SHELL: The name of the shell that starts when you open a terminal window. On most Linux distributions, this is bash unless you changed it from the default.
  • TERM: Terminal windows are in fact emulations of a hardware terminal. This contains the type of hardware terminal that will be emulated.
  • USER: The username of the current person using the system.
  • PWD: The path to the current working directory.
  • OLDPWD: The folder you were in before moving to the current working directory.
  • LS_COLORS: The list of color codes used by the ls highlights different file types.
  • MAIL: If the mail system is set up on your Linux machine (default is not the case), it will contain the path to the current user's mailbox.
  • PATH: A list of directories that are searched by the shell to find executable commands.
  • LANG: The language, localization, and character encoding settings.
  • HOME: The base directory of the current user.
  • _: The underscore ( _ ) environment variable contains the last command that was typed.

RELATED: Using Pushd and popd on Linux

We can see what some of these are going to use with nothing more advanced than echo that will write the values ​​to the terminal window . To see the value of an environment variable, you must add a dollar sign ( $ ) at the beginning of the name.

A nice touch is that you can use the tab completion to fill in the name of the environment variable for you. Type a few letters of the name and press Tab. The variable name is completed with the shell. If that doesn't happen, you'll need to type a few more letters to distinguish the environment variable from other commands with names that start with the same letters:

  echo $ SHELL 
  echo $ LANG 
  echo $ HOME 
  echo $ PWD 

  echo $ SHELL in a terminal window

To create your own global environment variables, add them to the / etc / environment file. You must use sudo to edit this file:

  sudo gedit / etc / environment 

  sudo gedit / etc / environment in a terminal window

To add an environment add variable, type the name, an equal sign ( = ) and the value that the environment variable should have. Do not put spaces before or after the equal sign ( = ). The environment variable name can contain letters, an underscore ( _ ), or numbers. However, the first character of a name cannot be a number.

If there are spaces in the value, make sure to enclose the whole value in quotes ( ").

 The / etc / environment file was opened in a editor and a new environment variable was added.

Save the file and then log out and log in again. Use echo to test if a new variable exists and has the value you set :

  echo $ WEBSITE 

  echo $ WEBSITE in a terminal window.

Since it is a global environment variable, and available to everyone, user mary can refer to the environment variable when they log in next time:

  echo $ WEBSITE 

  echo $ WEBSITE in a terminal window.

Type printv to see all environment variables at once. There is a lot of output, so it makes sense to pass it through sort and then to less :

  printv | sort | less 

  printv | sort | less in a terminal window.

The sorted list of environment variables is shown to us in less .

 sorted list of environment variables in less in a terminal window.

We can direct the output through grep to look for environment variables related to a particular topic.

  printv | grep GNOME 

  printv | grep GNOME in a terminal window.

RELATED: Graphically Editing Text Files on Linux Using Dit

Shell Environment Variables

These are some of the shell environment variables used in bash to dictate or record its behavior and functionality. Some values ​​are updated as you use the terminal. For example, the environment variable COLUMNS is updated to reflect the changes you could make to the width of the terminal window:

  • BASHOPTS: The command-line options used when bash was launched.
  • BASH_VERSION: The version number bash as a series of words and numbers.
  • BASH_VERSINFO: the bash version as a number.
  • COLUMNS: The current width of the terminal window.
  • DIRSTACK: The directories added to the directory stack by the pushd command. [19659015] HISTFILESIZE: Maximum number of lines allowed in the history file.
  • HISTSIZE: Number of lines history allowed in memory.
  • HOSTNAME: The host name of the computer.
  • IFS: The internal field separator separated input on the command line. By default this is a space.
  • PS1: The environment variable PS1 contains the definition for the primary, standard and command prompt. A set of tokens called escape strings can be included in the definition of your command prompt. They represent things like the host and username, the current working directory and the time.
  • PS2: When a command has more than one line and more input is expected, the secondary command prompt is displayed. The environment variable PS2 contains the definition of this secondary prompt, which is the greater than sign by default (> ).
  • SHELLOPTS: Shell options that you can set with the option set .
  • UID: The user ID of the current user.

RELATED: Using Pushd and popd on Linux

Let's take a look at some of these shell variables:

  echo $ BASH_VERSION 
  echo $ HOSTNAME 
  echo $ COLUMNS 
  echo $ UID 

  echo $ BASH_VERSION in an echo $ BASH_VERSION

For completeness, here are the tokens you can use in the command prompt definitions:

  • t: The current time, formatted as HH: MM: SS. [19659015] d: The current date, expressed as weekday, month, date.
  • n: A character with a new line.
  • s: The name of your shell.
  • W: The name of your current working directory.
  • w: The path to your current working directory.
  • u: The username of the person who is logged in.
  • h: The host name of the computer.
  • #: Every command within a shell is numbered. This will allow you to see the command number in your command prompt. This is not the same as the number that will have the command in the list history .
  • $: Sets the last character of the prompt to a dollar sign ( $ ) for a regular user and a hash symbol ( # ) for the root user . This works by checking the user's UID. If it is zero, the user is root.

You can find the definition of your environment variable PS1 in your .bashrc file.

Create Session Environment Variables [19659005] To create environment variables for your own use, add them to the bottom of your .bashrc file. To have the environment variables available for remote sessions, such as SSH connections, you must also add them to your .bash_profile file.

The format of the environment variable definition is the same for both files. To add a definition to your .bash_profile file, type it into your home directory:

  gedit .bashrc 

  .bashrc file will be converted to an editor and a new environment variable is added as the last line in the file.

We have added an environment variable called INHERITED_VAR . Note the word "export" at the beginning of the line.

 dit .bashrc in a terminal window.

Save and close your file after you have finished editing. You can log out and log in again, or you can have the shell reread the file .bash_profile with the dot command (. ) like this:

. .bashrc 

. .bashrc in a terminal window.

Now let's create an environment variable on the command line:

  LOCAL_VAR = "Only this session" 

  LOCAL_VAL = "This session only" in a terminal window.

Using echo we can see that both environment variables are accessible to us:

  echo $ LOCAL_VAR 

  echo $ LOCAL_VAR in a terminal

You will notice that the definition of the INHERITED_VAR environment variable had the word "export" at the beginning of the line. This means that the environment variable is inherited by underlying processes from the current shell. If we start another one with the bash command, we can check the two variables again, from the underlying shell:

  echo $ LOCAL_VAR 

  bash in a terminal window

As you can see, the INHERITED_VAR is accessible in the child shell, but LOCAL_VAR is not. We just get a blank line.

Although "export" adds the environment variable part to the environment inherited by child processes, INHERITED_VAR is not a global environment variable. For example, user mary cannot reference it:


  echo $ INHERITED_VAR in a terminal window.

To close our child session we use exit :


Inherited environments also affect scripts. Here is a simple script that writes the values ​​of our three environment variables to the terminal window:

  / Bin / bash


This was saved in a file named envtest.sh and then made executable with the following:

  chmod + x envtest.sh 

script accesses two of the three environment variables:

  ./ envtest.sh 

 ./ envtest.sh in a terminal window.

The script can see the WEBSITE global environment variable and the INHERITED_VAR exported environment variable. It cannot access LOCAL_VAR even though the script is executed in the same shell in which the variable was created.

If necessary, we can export an environment variable from the command line. We do that with our LOCAL_VAR and then run the script again:

  export LOCAL_VAR 
  ./ envtest.sh 

 export LOCAL_VAR in a terminal window.

The environment variable has been added to the environment of the current shell and thus exists in the environment inherited by the script. The script can also reference that environment variable.

Remote Connections

Global Environment Variables are accessible for remote login sessions, but if you want your locally defined environment variables to be available to you remotely, you must add them to your .bash_profile file. You can set the same environment variable in the files .bashrc and .bash_profile with different values. For example, this can be picked up by a script to modify its behavior for people using the system locally or remotely.

(At the risk of confusion, there is also a .profile file. It may also contain environment variable definitions. However, the file .profile is not read as the file .bash_profile is present, so the safest thing to do – and the bash – conforming way – is to use the .bash_profile file.)

To edit the .bash_profile file, we use gedit again:

  gedit .bash_profile 

 gedit .bash_profile in a terminal window.

We are going to add the same environment variable with the same value that we used before.

 The .bash_profile file has been opened in an editor and a new environment variable has been added.

Save your changes and close gedit . [19659006] On another computer we make a SSH connection to the test computer.

  ssh dave@howtogeek.local 

 ssh dave@howtogeek.local in a terminal window.

Once connected, we run the script again:

  ./ envtest.sh 

 ./ envtest.sh in a terminal window. [19659006] The .bash_profile file was read as part of the initialization of the remote login and the environment variable INHERITED_VAR is accessible to us and the script.

Disable an environment variable

Use the unset command to disable an environment variable. If we disable the global environment variable WEBSITE and the exported environment variable INHERITED_VAR they are no longer available on the command line, nor in underlying processes:

  disable WEBSITE 
  disable INHERITED_VAR [19659032] ./ envtest.sh 
  echo $ WEBSITE 

 Disabling an environment variable on Bash on Linux.

One point to note is that this only changes the availability of global environment variables for you in this session. Another person who is logged in at the same time can still access their copy of that global environment variable. His copy was initialized and read from the file / etc / environment during his login process and is independent of anyone else's copy of the variable.

As an example user mary still has access to the environment variable WEBSITE and can read its value even though user dave disabled it in his session:

  echo $ WEBSITE 

 echo% WEBSITE in a terminal window.

Environment Management

Environment variables can be used to let scripts and applications know how to behave. They can be used to store settings or small amounts of data. For example, a script can fill an environment with a value that can be referenced by other scripts without having to write them to a file.

Source link