13 May 2014 @ 7:57 AM 

Hello !

A new post after a long time…

 

As you know, the variables in bash are global by default (their scope is from the initialisation (usually when you start using it), to the destruction of the variable (usually at the end of the script). The variable will be available through all the functions within the script.

Now, if you want to reduce the scope of a variable, and tie it to a specific function, you usually render it unique (by starting with an underscore for instance), then initialise it at the beginning of your function, then destroy it (unset) at the end of the function.

There is another option : you can use the keyword “local” like in other languages.

Here is an example on how to use it :

#!/bin/bash

MyFunction () {

local TheVar

TheVar=1

echo “In The Function ${TheVar}”

}

declare -i TheVar

TheVar=99

echo “Before the Function ${TheVar}”

MyFunction

echo “After the Function ${TheVar}”

Here is the output :

Before the Function 99

In The Function 1

After the Function 99

And if you comment out the “local” part :

Before the Function 99

In The Function 1

After the Function 1

Another note on this.

According to my tests done on my bash version (GNU bash, version 3.2.51(1)-release), you can achieve the same results by simply declaring your variable within a function.

e.g.

#!/bin/bash

MyFunction () {

declare -i TheVar

TheVar=1

echo “In The Function ${TheVar}”

}

declare -i TheVar

TheVar=99

echo “Before the Function ${TheVar}”

MyFunction

echo “After the Function ${TheVar}”

Has  the following results :

Before the Function 99

In The Function 1

After the Function 99

Note also that, if you re-use the same variable name (as per our example) once you declare a local variable, the content of the global variable of the same name is not accessible within the function anymore !

e.g.

#!/bin/bash

MyFunction () {

#local TheVar

echo “Before declaration : ${TheVar}”

declare -i TheVar

echo “After declaration, before assignement : ${TheVar}”

TheVar=1

echo “After assignement : ${TheVar}”

}

declare -i TheVar

TheVar=99

echo “Before the Function ${TheVar}”

MyFunction

echo “After the Function ${TheVar}”

Gives the following results :

Before the Function 99

Before declaration : 99

After declaration, before assignement :

After assignement : 1

After the Function 99

Think about this the next time you do recursive functions, this might help. Counters (while [ i -lt 200 ];) should always be declared local within a function. Keep in mind also that “local” keyword is only available within a function.

Hope you enjoyed and see you next time !

Posted By: Dimi
Last Edit: 13 May 2014 @ 07:57 AM

EmailPermalinkComments (0)
Tags
Categories: Bash, Snippets

 Last 50 Posts
Change Theme...
  • Users » 66
  • Posts/Pages » 25
  • Comments » 4
Change Theme...
  • VoidVoid « Default
  • LifeLife
  • EarthEarth
  • WindWind
  • WaterWater
  • FireFire
  • LightLight