Showing posts with label Bash. Show all posts
Showing posts with label Bash. Show all posts

Friday, October 2, 2009

Variable Scoping In Bash Functions

Quick and dirty, people. Today I was testing some complex bash scripts that we wrote on my current project assignment -- those which should have been a python or pearl script to begin with -- and bumped into a problem concerning functions and variable scope.

Since I'm mainly a C* programmer (C, C++ and C#), my shellscript looks too much like a common program, admittedly. This means that I use a lot of functions. But there's a catch: variables used in bash are automatically global. So, if I execute the portion of code below:

#!/bin/bash
function test()
{
    value=123
    echo $value
}
value=321
echo $value
test                          
echo $value

I will get the following output:

321
123
123

Which isn't what I intended. So, I found this nice command that was secret to me, called "local". Variables in bash can be declared, and it's scope can be determined by using this command. So, the following script:

#!/bin/bash
function test()
{
    local value=123
    echo $value
}
value=321
echo $value
test
echo $value


Which would produce:

321
123
321

Which would be exactly what I desired.