How to Read and Set Environment Variable in Bash

Introduction to Read and Set Environment Variable in Bash

Guide to Read and Set Environment Variable in Bash – When you use a bash session to connect with your server, your terminal compiles a lot of information to define its behavior and access to resources. Some of these parameters are decided by user input, while others are contained inside configuration settings.

The bash keeps track of all of these settings and data in part by maintaining a region called the environment. Every time the bash starts a session, it creates an environment that contains variables that determine system properties.

We’ll go through how to interact with the environment and read and set environmental and bash variables both interactively and via configuration files in this tutorial.

How the Environment and Environmental Variables Work

When a shell session starts, a process gathers and compiles information that the shell process and its child processes should have access to. The information for these parameters comes from a number of files and settings on the machine.

The environment offers a means for the shell process to get or change settings, which it then passes on to its child processes.

Strings representing key-value pairs are use to implement the environment. If more than one value is supplied, colon (:) characters are usually use to divide them. In general, each pair will resemble the following:


If the value contains significant white space, quotations are use:

KEY="value with spaces"

The keys in these scenarios are variables. They can be one of two types, environmental variables or shell variables.

Environmental variables: are variables defined for the current shell that is passed down to any child shells or processes. Environmental variables are use to send data to shell-spawned processes.

Shell variables: are variables that exist only in the shell in which they were created or declared. They’re frequently use to store temporal data, such as the current working directory.

These variables are frequently written in all capital letters as a matter of habit. This makes it easier for users to recognize environmental elements in different scenarios.

Printing Shell and Environmental Variables

Each shell session has its own set of shell and environmental variables to keep track of. These can be access in a variety of ways.

Using the env or printenv commands, we can get a list of all of our environmental variables. They should all work the same in their default state:

$ printenv

This is quite typical of both printenv and env output. The only distinction between the two commands is their more precise functionality. You may, for example, use printenv to get the values of specific variables:

$ printenv PATH

By putting a collection of variable definitions into a command like this: env, on the other hand, you may change the environment in which programs execute.

$ env VAR1="value" command_to_run command_options

Because, as we mentioned earlier, child processes normally inherit the parent process’s environmental variables, you can override settings or add extra variables for the child.

As you can see from the result of our printenv command, our system files and processes have built up quite a few environmental variables without our involvement.

These display environmental variables, but what about shell variables?

This may be accomplish with the set command. We can receive a list of all shell variables, environmental variables, local variables, and shell functions by typing set without any other parameters:

$ set

Normally, this is a lengthy list. To deal with the volume of output, you should probably pipe it through a pager program:

$ set | less

Common Environmental and Shell Variables to Read and Set Environment Variable

Some shell and environmental variables are quite valuable and are frequently use. Here are some of the most typical environmental variables you’ll experience:

  • SHELL: This describes the shell that will be interpreting any commands you type in. In most cases, this will be bash by default, but other values can be set if you prefer other options.
  • TERM: This specifies the type of terminal to emulate when running the shell. Different hardware terminals can be emulate for different operating requirements. You usually won’t need to worry about this though.
  • USER: The current logged in user.
  • PWD: The current working directory.
  • OLDPWD: The previous working directory. This is kept by the shell in order to switch back to your previous directory by running cd -.
  • LS_COLORS: This defines color codes that are use to optionally add colored output to the ls command. This is use to distinguish different file types and provide more info to the user at a glance.
  • MAIL: The path to the current user’s mailbox.
  • PATH: A list of directories that the system will check when looking for commands. When a user types in a command, the system will check directories in this order for the executable.
  • LANG: The current language and localization settings, including character encoding.
  • HOME: The current user’s home directory.
  • _: The most recent previously executed command.

Setting Shell and Environmental Variables to Read and Set Environment Variable

I will give a little demonstration to help you understand the distinction between the shell and environmental variables, as well as the syntax for setting them.

Creating Shell Variables

we’ll start establishing a shell variable. It’s simple to do; all we have to do is give it a name and a value. We’ll maintain the variable name in all capitals and set it to a plain string as per usual.

$ TEST_VAR='Hello World!'

Because the value of our variable contains a space, we’ve used quotations here. Furthermore, we utilized single quotes because the exclamation point is a particular character in the bash shell that, if not escaped or enclosed in single quotes, expands to the bash history.

We now have a shell variable. This variable exists in our current session, but it will not be pass on to child processes.

We can observe this by searching the set output for our new variable:

$ set | grep TEST_VAR

By trying the same thing with printenv, we can confirm that this isn’t an environmental variable:

$ printenv | grep TEST_VAR

There should be no output return.

Let’s use this as a chance to show how to get the value of any shell variable or environmental variable.

$ echo $TEST_VAR

As you can see, the value of a variable is reference by using the $ sign before it. When the shell encounters this, it interprets it to signify that it should substitute the variable’s value.

As a result, we now have a shell variable. It should not be hand down to any subsequent procedures. To demonstrate, we may start a new bash shell from within our present one:

$ bash
$ echo $TEST_VAR

Nothing will be return if we type bash to start a child shell and then try to read the contents of the variable. This is just what we had hoped for.

Type exit to return to our old shell:

$ exit

Creating Environmental Variables

Let’s now make our shell variable an environmental variable. This may be accomplish by exporting the variable. To do so, apply the following command:

$ export TEST_VAR

As a result, our variable will become an environmental variable. We can double-check this by looking at our environmental listing once more:

$ printenv | grep TEST_VAR

Our variable appears this time. Let’s attempt our experiment again, this time using our child shell:

$ bash
$ echo $TEST_VAR

Great! The variable set by our parent shell has been sent to our child shell. Let’s attempt to export another variable before we depart this child shell. In a single step, we may establish environmental variables like this:

$ export NEW_VAR="Testing export"

Test that it’s export as an environmental variable:

$ printenv | grep NEW_VAR

Now, let’s exit back into our original shell:

$ exit

Let’s see if our new variable is available:

$ echo $NEW_VAR

Nothing is return. Because environmental variables are only provided to child processes, this is the case. There is no built-in technique to set the parent shell’s environmental variables. In most circumstances, this is a positive thing since it prevents programmes from interfering with the operating environment from which they were invoked.

In our child shell, the NEW VAR value was set as an environmental variable. This variable would be accessible to itself as well as any of its child shells or processes. That environment was gone when we returned to our primary shell.

Demoting and Unsetting Variables

We still have our TEST_VAR variable defined as an environmental variable. We can change it back into a shell variable by typing:

$ export -n TEST_VAR

It is no longer an environmental variable:

$ printenv | grep TEST_VAR

However, it is still a shell variable:

$ set | grep TEST_VAR

If we want to completely unset a variable, either shell or environmental, we can do so with the unset command:

$ unset TEST_VAR

We can verify that it is no longer set:

$ echo $TEST_VAR

Nothing is returned because the variable has been unset.

Setting Environmental Variables at Login

Many programmes, as we’ve already discussed, employ environmental factors to determine how to run. We don’t want to have to set up crucial variables every time we start a new shell session, and we’ve previously seen how many variables are already set up when we log in, so how can we create and define variables automatically?

Due to the multiple configuration files that the bash shell reads depending on how it is launched, this is a more complicated problem than it appears.

Implementing Environmental Variables

As you can see, there are a lot of different files that we’d need to look at while setting up our settings.

This gives us a lot of flexibility, which is useful in situations where we want some settings in a login shell and others in a non-login shell. In most cases, though, we’ll want the same settings in both circumstances.

Most Linux distributions, fortunately, set the login configuration files to use the non-login configuration files as a source. This implies you may provide environmental variables in both the login and non-login configuration files. They’ll be read in both circumstances after that.

We’ll almost always be configuring user-specific environmental variables, and we’ll want those settings to work in both login and non-login shells. This means that these variables should be defined in the ~/.bashrc file.

Now open the following file:

$ nano ~/.bashrc

This will very likely already have a lot of information in it. The majority of the definitions in this section are for bash options, which have nothing to do with environmental variables. You may use the command line to set environmental variables as well:

$ export VARNAME=value

Any additional environmental variables can be added to the ~/.bashrc file as long as they aren’t in the middle of another command or for loop. The file may then be saved and closed. Your environmental variable declaration will be read and provided to the shell environment the next time you start a shell session. By typing: you can force your current session to read the file right now.

$ source ~/.bashrc

If you need to set system-wide variables, you may want to think about adding them to /etc/profile, /etc/bash.bashrc, or /etc/environment.

Conclusion of How to Read and Set Environment Variable in Bash

Environmental and shell variables are always there and may be quite beneficial in your shell sessions. They’re a fun method for a parent process to establish configuration parameters for its offspring outside of files.

This has a lot of benefits in certain situations. Some deployment strategies, for example, use environmental variables to configure authentication data. This is advantageous since it eliminates the need to store these in files that may be accessed by third parties.

There a plenty of additional, more ordinary, but more typical instances in which you’ll need to read or change your system’s environment. These tools and strategies should provide you with a solid basis for developing and implementing these adjustments.

That’s all for this article if you have any confusion contact us through our website or email us at [email protected] or by using LinkedIn

Suggested Articles:

  1. How to Switch or Change Users in a Linux Shell
  2. Guide to Bash Variable in String

Leave a Comment