Free Hosting Online for WorkStations

< Previous | Contents | Next >

Local Variables

In the scripts we have written so far, all the variables (including constants) have been global variables. Global variables maintain their existence throughout the program. This is fine for many things, but it can sometimes complicate the use of shell functions. Inside shell functions, it is often desirable to have local variables. Local variables are only ac- cessible within the shell function in which they are defined and cease to exist once the shell function terminates.

Having local variables allows the programmer to use variables with names that may al- ready exist, either in the script globally or in other shell functions, without having to worry about potential name conflicts.

Here is an example script that demonstrates how local variables are defined and used:


#!/bin/bash


# local-vars: script to demonstrate local variables

#!/bin/bash


# local-vars: script to demonstrate local variables


foo=0

# global variable foo

foo=0


funct_1 () {

local foo # variable foo local to funct_1 foo=1

echo "funct_1: foo = $foo"

}


funct_2 () {

local foo # variable foo local to funct_2 foo=2

echo "funct_2: foo = $foo"

}


echo "global: foo = $foo" funct_1

funct_1 () {

local foo # variable foo local to funct_1 foo=1

echo "funct_1: foo = $foo"

}


funct_2 () {

local foo # variable foo local to funct_2 foo=2

echo "funct_2: foo = $foo"

}


echo "global: foo = $foo" funct_1

Local Variables


echo "global: foo = $foo" funct_2

echo "global: foo = $foo"

echo "global: foo = $foo" funct_2

echo "global: foo = $foo"


As we can see, local variables are defined by preceding the variable name with the word local. This creates a variable that is local to the shell function in which it is defined. Once outside the shell function, the variable no longer exists. When we run this script, we see the results:



[me@linuxbox ~]$ local-vars

global: foo = 0 funct_1: foo = 1 global: foo = 0 funct_2: foo = 2 global: foo = 0

[me@linuxbox ~]$ local-vars

global: foo = 0 funct_1: foo = 1 global: foo = 0 funct_2: foo = 2 global: foo = 0


We see that the assignment of values to the local variable foo within both shell functions has no effect on the value of foo defined outside the functions.

This feature allows shell functions to be written so that they remain independent of each other and of the script in which they appear. This is very valuable, as it helps prevent one part of a program from interfering with another. It also allows shell functions to be writ- ten so that they can be portable. That is, they may be cut and pasted from script to script, as needed.


Top OS Cloud Computing at OnWorks: