Friday, June 8, 2007

Executing a Shell script

Its very useful and handy thing to know different ways to execute shell script. Find out how by the below

Description : Lets have a shell script "test.sh" with code as shown below:

#!/bin/bash

export STRING="Hello Mate" # Intialization of a string variable.

Now, consider the below scenario

Scenario 1) :
--> Excute the below steps on your command line:
$ ./test.sh
$ echo $STRING

--> Output: The command "echo $STRING" would give you empty string.

Scenario 2) :
--> Excute the below steps on your command line:
$ . ./test.sh <<< See the difference in executing w.r.t scenario 1
$ echo $STRING

--> Output: The command "echo $STRING" would give you "Hello Mate".

Reason: The fact is in first scenario, the shell script gets executed in its child shell, due to which the variables set by the script is lost in the parent shell once the shell script is executed in child shell and returns to the parent shell.
This is overcome in second scenario, in this scenario the shell script is executed in the parent shell itself, due to which all the variables set are not lost.

All this happened because the way of executing Shell script differed in the Scenario 1 and Scenario 2.





2 comments:

Santosh said...

Super!!!
Knew this command, but didn't know why?

Thanks,
Santosh

Unknown said...

this is a very useful information. Nice post.