Whenever we declare a variable in a script, it is accessible to all functions. The variable is global by default. If the variable is modified by any line of script or any function, it will be modified in global scope. This may create problems in certain situations. We will see this problem in the following script, function_12.sh
:
function_12.sh
#!/bin/bash
name="John"
hello()
{
name="Maya"
echo $name
}
echo $name # name contains John
hello # name contains Maya
echo $name # name contains Maya
Test the script as follows:
$ chmod +x function_12.sh
$ ./function_12.sh
This should produce the following output:
Output:
JohnMayaMaya
To make a variable local, we declare it as follows:
local var=valuelocal varName
Let’s write the script function_13.sh
as follows:
function_13.sh
#!/bin/bash
name="John"
hello()
{
local name="Mary"
echo $name
}
echo $name # name contains John
hello # name contains Mary
echo $name # name contains John
Test the script as follows:
$ chmod +x function_13.sh
$ ./function_13.sh
Output:
Output:
JohnMaryJohn
The local
command can only be used within a function. The local
keyword limits the scope of the variable to the function. In the previous script, we initially declared the name
variable; it has global scope. This name
variable has the content John
. Then, we have declared the local
variable name
in the hello
function. This local variable name
is initialized to Mary
. Then, outside of the hello
function, we again access the global variable name
, which has the content John