Dave Dave - 4 months ago 19
Bash Question

Define a local array in a bash function and access it outside that function

I am trying to define a local array in a bash function and access it outside that function.

I realise that BASH functions do not return values but I can assign the results of a calculation to a global value. I expected this code to echo the content of array[] to the screen. I'm not sure why its failing.

function returnarray
{
local array=(foo doo coo)
#echo "inside ${array[@]}"
}


targetvalue=$(returnarray)
echo ${targetvalue[@]}

Answer

You have two options. The first one is what @choroba prescribes, and it's probably the best and simplest: don't define your array local.

returnarray() {
    array=(foo doo coo) # NOT local
}

# call your function
returnarray
# now the array is in array and you may copy it for later use as follows:
targetvalue=( "${array[@]}" )
# print it to check:
declare -p targetvalue

This is neat, simple, safe, completely avoids the use of subshells (so it's more efficient). It has one caveat, though: it won't work with sparse arrays (but this should be a minor detail). There's another tiny disadvantage: the array needs to be copied.


Another option is to pass a variable name to your function, and have the function generate the array directly. This uses namerefs and is only available since Bash 4.3 (but it's really good—use it if you can!):

generatearray() {
    # $1 is array name in which array is generated
    local -n array="$1" || return 1
    array=( foo doo coo )
}
# call function that constructs the array with the array name
generatearray targetvalue
# display it
declare -p targetvalue