SCOPE of Variables

By niharcsql

SETTING ENVIRONMENT VARIABLES by the help of export command

Normally all our variables are local. Local variable can be used in same shell, if you load another copy of shell (by typing the /bin/bash at the $ prompt) then new shell ignored all old shell’s variable. For e.g. Consider following example

$ myvar=NIHAR
$ echo $myvar
NIHAR
$ /bin/bash
$ echo $myvar

NOTE:-Empty line printed
This is due to the variable ‘myvar’ has only scope to the previous SHELL. That has the value “NIHAR” which has no scope to the /bin/bash SHELL. As there is no value assigned to the variable ‘myvar’ it shows the value of ‘myvar’ as empty. This can be solved by the export command
$ myvar=Papu
$ echo $myvar

Papu
$ exit
$ echo $myvar

NIHAR

Global shell defined as:
You can copy old shell’s variable to new shell (i.e. first shells variable to seconds shell), such variable is know as Global Shell variable.

To set global varible you have to use export command.
Syntax:
$ export variable1, variable2,…..variableN

Examples:
$ myvar=NIHAR
$ echo $myvar
NIHAR
$ export myvar
$ /bin/bash
$ echo $myvar
NIHAR
$ exit
$ echo $myvar

Nihar

Here one problem is arising. The export command set the value of ‘myvar’ for all SHELLs. That means the value of variable ‘myvar’ will have the same value in each SHELL . Suppose we do not want to see the same value of the variable ‘myvar’ in another SHELL what can be done?

Tags:

Leave a Reply