• Arun Kumar

Environment Variables in Linux

Linux environment variables are backbone of Linux operating system. A variable stores a value and gives you flexibility to call the variable in any shell script. In this article we will understand how to set environment variables in Linux.


Set Environment Variable in Linux


You can define a linux variable using export command

export <variable-name>=<value>

export MY_WEBSITE=dbagenesis.com
export ARTICLE="Environment Variables in Linux"
export TODAY="It's an exciting day"
export PLAYER='The "ROCK" player'

Please Note

  • Always use UPPERCASE for variable names

  • Put value under " " if it contains spaces or single quotes

  • Put value under ' ' if it contains double quotes

You can check the value of a stored environment variable using echo command

echo "Current website is $MY_WEBSITE"
echo "You are reading $ARTICLE"

You have to use $ when you want to call a variable's stored value.

We don't put $ sign while exporting a linux variable, we put $ sign only while calling variables


Scope of Environment Variables


When you set environment variables using linux export command, these variables scope is only session level. You close the terminal and login again, the variables are cleared from the system.


To make the variables permanent so that they are available when you login again, you must set the variables inside .bashrc file last line

vi .bashrc                      --> user's home location      

export MY_WEBSITE=dbagenesis.com
export ARTICLE="Environment Variables in Linux"

You need to source (or load) the .bashrc for Linux to load new environment variables

source .bashrc

echo $MY_WEBSITE
echo $ARTICLE

The variables set under .bashrc file are only available to the particular user. For example, if Oracle user sets environment variables under its own .bashrc file, then its only accessible to Oracle user.


To define system wide environment variables, add variables to /etc/environment file (last line)

As root user:
=============
vi /etc/environment

export MY_SYS_VAR="System Wide Variable"

Logout and login. Now MY_SYS_VAR is available to all the users on Linux server!



List Environment Variables


To list all the system variables and local variables (set by user), simply use env command

env

To filter all the variables listed by env command

env | grep MY                --> prints all vars containing MY
env | grep HOME              --> prints all vars containing HOME

Enjoy! 🐝🐝🐝




398 views

Recent Posts

See All