How to set and execute environment and shell variables in Linux?

Overview

When we connect to our server through a shell session, shell gathers a variety of pieces of information to understand its behaviour and access to resources. Some of these settings are controlled by configuration settings, while others are decided by user input. The environment, which the shell maintains, is one way it keeps track of all these settings and particulars. Every time a session is started, the shell creates an area called the environment, which contains variables that specify system properties.

In this tutorial, we'll examine Linux environment variables in more detail, including what they are, how they differ from shell variables, types of sessions, and how to list, set, unset, and manage them.

Prerequisites

There are certain prerequisites that need to be met before you begin:

What are environment variables in Linux?

Environment variables are the dynamic quantities, that have an impact on each computer operations or programs. Despite having different types, they are present in all operating systems. Environment variables can be created for the current shell, and may be inherited by other child shells or processes. It is possible to create, update, save, and delete environment variables, which provide data for operation of the system.

These kinds of variables are conventionally and wholly defined in capital letters. This aids users in differentiating environmental variables amongst another context.

Scope of Environment Variable:

The portions of a programme or environment that can access a specific variable are referred to as the variable's scope. Linux allows for the global and local scope of an environment variable.

  • Globally scoped variables: Globally scoped Environment variables are accessible from anywhere within the particular environment of the terminal.

  • Locally scoped variables: The locally scoped environment variable can only be accessed from the terminal in which it is defined, no other script or programme may do so.

What are Shell Variables?

Shell variables are variables that only exist inside the shell in which they were defined or set. They are frequently employed to maintain ephemeral data, such as the current working directory. These variables are used to temporarily store the values.

Scope of Shell Variables:

Shell variables are not passed down to children, but environment variables are. Moreover, each shell file such as bash and zsh have their own set of shell variables.

Commonly used Environment and Shell Variables:

Some environment and shell variables are quite helpful and frequently used. You may frequently encounter the following environment variables:

VariablesDescription

HOME

Specifies the home directory of the current user.

USER

shows the current logged in user.

SHELL

Explains the shell that will interpret any commands you type. Typically, bash will be the default, but you can change it anytime you want.

PWD

PWD stands for “Print Working Directory”. This command gives the path of your current working directory.

Shows an index of the directories that the system will search through to find commands. The system will search folders in this sequence for the executable when a user types a command.

TERM

Indicates the kind of terminal to simulate while running the shell. For various operational requirements, several types of hardware terminals can be used. Usually, you need not to worry about this.

UID

Specifies the current user’s unique identifier.

MAIL

Gives the path to current user’s mailbox.

_

Helps access the most recently executed previous command in the terminal.

OLDPWD

Specifies the previous working directory. You can switch back to your previous working directory by running the command cd -.

LANG

Displays the current language, localization and character encoding etc. and its settings.

Additionally, you’ll often see the following variables while working with the shell:

Variables Description

BASH_VERSION

This prints the current version of bash being executed, that too in a human readable format.

COLUMNS

This command shows the number of columns that are being used to draw the output.

HOSTNAME

This command gives the hostname of the computer.

BASH_VERSINFO

Provides the current version of bash in a machine-readable format.

Step 1: Creating Shell Variable

To begin, we'll make a shell variable for the current session by just specifying a name and a value.

$ DEMO_VAR='My first program!'

Our current session has access to this shell variable, but it won't be shared with any child processes. You can verify this by grepping for our new variable along with the set command:

$ set | grep DEMO_VAR

In a collection of files, the grep command can look for a string. When it discovers a pattern that corresponds to more than one file, it prints the name of the file, followed by a colon, and then the line that corresponds to the pattern.

Step 2: Printing Shell and Environment Variables:

Use the following command to view a list of all (global) environment variables that are accessible to the current user:

$ printenv

Note: Output of the printenv command can be piped to the less command. The command less is a Linux programme that can be used to read a text file’s one page (or one screen) at a time, as it accesses files page by page instead of the entire file and provides fast access time.

$ printenv | less

Step 3: Exporting Environment Variables

Let's now convert the shell variable to an environment variable. Exporting the variable will allow us to achieve this. The following command will help you do so:

$ export DEMO_VAR

You can verify this by running the following command:

$ printenv | grep DEMO_VAR

Unsetting Environment Variables

Our DEMO VAR variable is still defined as an environmental variable. We can convert it back into a shell variable, by typing the following command:

$ export -n DEMO_VAR

It's no longer an environment variable now, which u may check using the following command:

$ printenv | grep DEMO_VAR

Let's check if it is still a shell variable or not, using the command below:

$ set | grep DEMO_VAR

However, if you completely want to unset the variable, be it shell or environment, the following command will be used:

$ unset DEMO_VAR

You may verify the unsetting by running the following command:

$ echo $DEMO_VAR

We got nothing in the output as the variable has been completely unset.

Difference between Login, Non-Login, Interactive, and Non-Interactive sessions

Before moving to the next step, you need to understand the basics of above said 4 sessions, as depending on the method used to launch the session, the bash shell reads several configuration files.

  • Login shell: A login shell is a shell session that starts with user authentication. Your shell session will be set as a login shell if you are authenticating using SSH or a terminal session. A login session will initially read configuration information from the /etc/profile file.

  • Non-login shell: A non-login shell session is started when you start a new shell session via already authenticated terminal. A non-login shell builds its environment by first reading the user-specific /.bashrc file and then /etc/bash.bashrc.

  • Interactive shell: An attached shell session to a terminal is referred to as an interactive shell session. An interactive login shell is typically used to start an interactive SSH session.

  • Non-Interactive shell session: A non-interactive shell is one that does not communicate with the user. You can access them with a script or similar file system. Additionally, these shell sessions can be executed through automated processes.

Step 5: Environment Variables Implementation

We would typically need to look at several files of various categories to configure our preferences. This offers a great deal of flexibility that can be helpful in specific circumstances where we want to put some settings in the login/current shell and other settings in a non-login shell. But in most cases, we'll prefer same settings in both circumstances.

Fortunately, most Linux distributions set up the current shell's login configuration files to source the non-login configuration files. This implies that you can define the environment variables you wish in both login and non-login configuration files at the same time.

Typically, we'll be configuring user-specific environment variables, and we'll want those settings to work in login and non-login shells. This indicates that the .bashrc file is where these variables should be defined.

Now we need to open the following file:

$ nano ~/.bashrc

This file may already contain some information. The majority of these definitions pertain to bash settings and options, which have nothing to do with environment variables. Meanwhile, you can set the environment variables through the command line:

$ export VARNAME=value

In the /.bashrc file, any new environment variables may be introduced anywhere as long as they are not inserted in the middle of a command or loop. The file can then be saved and closed. Your environment variable declaration will be read and added to the shell environment the following time you launch a shell session. By entering, you can immediately compel your current session to read the file.

$ source ~/.bashrc

Exit the shell by entering the following command:

$ exit

Conclusion:

Your shell sessions always include environmental and shell variables, both of which are quite helpful. They offer an intriguing method for setting configuration information of the parent's process, which can also be used by the child processes. Moreover, with such variables, you can specify settings without using files.

In special situations, this provides lots of benefits. For instance, some deployment procedures use environment variables to configure authentication data. This is advantageous since it avoids maintaining the data in files that could be easily accessed by third parties.

There are numerous other, less interesting but more typical situations when you will need to read or modify the environment of your system. You should have a firm foundation for making these modifications and applying them appropriately after using these commands and procedures.

With this tutorial, you should be able to use environment variables on your Linux server. They can be effective tools for scripting, creating applications, and generally improving your experience using the shell.

Last updated