Global variable and export command in shell script

Variable holds a value and have a name. We have already declared lots of variables and see how they worked. If you don’t know what I am talking about check out our shell scripting section and for the detail variable talks, see variables in shell script. Those variables are the local variables, which means variables are only limited to that particular shell script. Thus, the local variable has only meaning when that particular shell script runs. But, global variable is broad and different. The global variables once declared works in all the shell scripts which saves lot of time and effort.

To declare the global variable the export command is used.

export variable_name

Let us take an simple example of two shell scripts to understand the global variable.

Script name: test1

export name
echo "LinuxBlog:$name"
sh test2

The first line of the code in this script file declares a global variable called “name”. The value is assigned to it then it is printed on the screen. The last line of the code takes us to another shell script test2.

Script name: test2

echo "Global variable displayed:::$name"

The test2 prints the global variable called “name”.Yes, we have already declared the variable “name” in test1 as a global variable. Let’s run the script test1 and see the output.

Global Variable in shell script

As you can see, the first echo is printed with the variable name and the last line directs to test2 script file which again prints the name(not declared in test2 but declared in test1 as a global variable).

Posted in Shell Scripting | Tagged , , | Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>