Using local variables in functions for Linux bash script

April 26, 2021

Comments

Adsense

Adsense

Adsense

Adsense

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.

Satish Kumar

Satish Kumar

I am Satish Kumar, Founder of LinuxConcept. Linux and F.O.S.S enthusiast, love to work on open source platform and technologies.

Adsense

Adsense

Adsense

Adsense

Adsense

Adsense

Adsense

Adsense

Adsense

Related Posts

Backup of files in Linux using command line

In IT or our day-to-day computer industry activities, taking backup is one of the most important activities. Previously, offices were required to keep important paper in a safe place; but if a fire breaks out, then everything is finished. In the digital world, taking...

Using awk in Linux

awk is a program that has its own programming language for performing data-processing and generating reports. The GNU version of awk is gawk. awk processes data, which can be received from a standard input, input file, or as the output of any other command or process....

0 Comments

0 Comments

Submit a Comment

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

18 − eight =

News & Updates

Join Our Newsletter

Adsense

Adsense

Adsense

Adsense