scope of variables

By niharcsql
Open a terminal and Run the command 
$ MYVAR=hello
Create a file named EX1.sh and add the following contents in the file
#!/bin/sh
echo "MYVAR is: $MYVAR"
MYVAR="hi there"
echo "MYVAR is: $MYVAR"
Run the script
$./EX1.sh
OUTPUT:
MYVAR is:
MYVAR is: hi there

What is happening here?
When you call EX1.sh from your interacvive shell, a new shell is worked to run the script.this is partly becoz of the
 #/bin/sh line at the begining of the script, We need to export the variable for itto be inherited by another program.
Run the following command
$ export MYVAR
$ ./EX1.sh
OUTPUT
MYVAR is: hello
MYVAR is: hi there

Now in the 1st line of the output, the value of MYVAR is “hello” But there is no way that this will be passed back to your interactive shell. Try reading the value of MYVAR

$ echo $MYVAR
hello
$

Once the shell script exits, its environment is destroyed. But MYVAR keeps its value of hello within your interactive shell. In order to receive environment changes back from the script, we must source the script - this effectively runs the script within our own interactive shell, instead of spawning another shell to run it. We can source a script via the "." command:

Open another Terminal and run the following command
$ MYVAR=hello
$ echo $MYVAR
OUTPUT:
hello
$ . ./EX1.sh
MYVAR is: hello
MYVAR is: hi there
$ echo $MYVAR
hi there
In the above command MYVAR variable just inherits the value of MYVAR from Global scope temporarily.
This will not affect other files(What was happened using export command. create another file named EX2.sh
and add the following instructions
#!/bin/sh
echo "MYVAR is: $MYVAR"
MYVAR="hi there"
echo "MYVAR is: $MYVAR"
Run the script.See What happens

$./EX2.sh
OUTPUT:
MYVAR is:
MYVAR is: hi there
we are using the same variable in EX2.sh, But it is not displaying the value of the Global variable MYVAR.
It displaying the empty value.

One Response to “scope of variables”

  1. SCOPE of Variables « Nihar Paital’s Script Says:

    [...] Paital’s Script Just another WordPress.com weblog « Hello world! scope of variables [...]

Leave a Reply