Linux Environment Variables, What to Know

Bash shell has a concept of environment variables. The purpose is to store information about the shell session and the working environment. Also, it stores the data in memory. So other programs and scripts (in the current shell) can access it.

Global environment variables

Global environment variables are visible from the shell session and from any spawned child subshell.

How to view global variables

You can use the printenv command to view the global variables. It works in any bash shell.

$ printenv
[...]
USER=christine
[...]
PWD=/home/christine
HOME=/home/christine
[...]
TERM=xterm
SHELL=/bin/bash
[...]
HISTSIZE=1000
[...]
$

How to view the individual local variable

$ printenv HOME
/home/christine
$
$ env HOME
env: 'HOME': No such file or directory
$

You can also use the echo command to display a variable’s value. When referencing an environment variable. In this case, you must place a dollar sign ($) before the environment variable name:

$ echo $HOME
/home/christine
$

$ ls $HOME
Desktop         Music      NetworkManager.conf                 Templates
Doc.tar         Music.tar  OldDocuments                        test_file
Documents       my_file    Pictures                            test_one
Downloads       my_scrapt  Public                              test_two
hlink_test_one  my_script  really_ridiculously_long_file_name  Videos
log_file        my_scrypt  slink_test_file
$

Local environment variables

Local variables are available only in the shell that creates them. Even though they are local, they are just as important as global environment variables.

The Linux system also defines standard local environment variables for you by default. However, you can define your local variables.

How to view local variables

To view the local variables, you can use the set command.

$ set
BASH=/bin/bash
[...]
HOME=/home/christine
[...]
PWD=/home/christine
[...]
SHELL=/bin/bash
[...]
TERM=xterm
[...]
USER=christine
[...]
colors=/home/christine/.dircolors
my_variable='Hello World'
[...]
_command ()
{
[...]
$

set, env, and printenv commands differences

envprintenvset
Do not sort the variables, nor include local environment variables, local user-defined variables, or local shell functions.Do not sort the variables, nor include local environment variables, local user-defined variables, or local shell functions.It displays global and local environment variables, user-defined variables, and local functions. It also sorts the display alphabetically.
It has additional functionalities.
set, env, and printenv commands differences

Related

Author: Srini

Experienced software developer. Skills in Development, Coding, Testing and Debugging. Good Data analytic skills (Data Warehousing and BI). Also skills in Mainframe.