Global variables, and their scope in Bash.

Shahar Dag dag at cs.technion.ac.il
Mon Dec 14 10:09:40 UTC 2009


----- Original Message ----- 
From: "Ray Parrish" <crp at cmc.net>
To: "Ubuntu user technical support,not for general discussions" 
<ubuntu-users at lists.ubuntu.com>
Sent: Monday, December 14, 2009 2:22 AM
Subject: Global variables, and their scope in Bash.


> Hello,
>
> I have a global variable called LoopCount, that I want to access, and
> write to in four different functions. The functions are as follows, [not
> actual code, just showing function names] -
>
> ReadintoArray [
>     # Loop with LoopCount, then reset it to zero.
> }
> WriteTopSection {
>     # Loop with LoopCount, then decrement it one.
> }
> WriteDescriptionSection {
>     # Loop with LoopCount starting where WriteTopSection left off.
> }
> WriteEndSection {
>     # Loop with LoopCount starting where WriteDescriptionSection left off.
> }
> # Main Program
> declare -i LoopCount
> ReadintoArray
> WriteTopSection
> WriteDescriptionSection
> WriteEndSection
>
> The problem I am having, is that in the ReadintoArray section the global
> variable LoopCount gets modified, and I have to reset it to zero at the
> end to get WriteTopDescription to start in the proper place.
>
> Then perversely the ending value of LoopCount does not get carried
> forward from WriteTopSection to WriteDescriptionSection, but instead is
> once again at the value of zero.
>
> Why in the world can my ReadintoArray function modify the value of the
> global variable LoopCount, but the next function down cannot?
>
> Does anyone have any light they can shed on the behavior of global
> variables in Bash?
>
> Thanks, Ray Parrish
>
>
> The Future of Technology.
> http://www.rayslinks.com/The%20Future%20of%20Technology.html
> Ray's Links, a variety of links to usefull things, and articles by Ray.
> http://www.rayslinks.com
> Writings of "The" Schizophrenic, what it's like to be a schizo, and other
> things, including my poetry.
> http://www.writingsoftheschizophrenic.com
>
>
>
> -- 
> ubuntu-users mailing list
> ubuntu-users at lists.ubuntu.com
> Modify settings or unsubscribe at: 
> https://lists.ubuntu.com/mailman/listinfo/ubuntu-users
>

Just a wild guess
Did you try to declare LoopCount before the functions

declare -i LoopCount
ReadintoArray [
     # Loop with LoopCount, then reset it to zero.
 }
 WriteTopSection {
     # Loop with LoopCount, then decrement it one.
 }
 WriteDescriptionSection {
     # Loop with LoopCount starting where WriteTopSection left off.
 }
 WriteEndSection {
     # Loop with LoopCount starting where WriteDescriptionSection left off.
 }
 # Main Program
 ReadintoArray
 WriteTopSection
 WriteDescriptionSection
 WriteEndSection

Shahar





More information about the ubuntu-users mailing list