Local Variables and Return Values in BASH

In this post, I’ll discuss some lessons learned from BASH programming, in particular, how to pass return values from BASH’s “functions”. BASH does not provide support scoped variables by default, so variables declared in a function are available everywhere once the function has been called. BASH will let you declare local variables within a function through the local keyword. Returning values is then a matter of echoing them out.

You can declare a function using the function keyword. (You don’t have to, but I think it’s more readable that way.) Below we have a function with some local variables, which we pass to a locally declared array, arr. We then echo the local array out.

function foo() {
    local a=2
    local b=3
    local declare -a arr=()
    arr=( ${arr[@]} $a )
    arr=( ${arr[@]} $b )
    echo ${arr[@]}
}

We can then collect the array containing the variables using the following code.

result=($(foo))
echo ${result[0]}
echo ${result[1]}