Global variables, and their scope in Bash.

Ray Parrish crp at cmc.net
Mon Dec 14 00:22:37 UTC 2009


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






More information about the ubuntu-users mailing list