tags:

views:

1641

answers:

5

How can I pass an array as parameter to a bash function?

Note: After not finding an answer here on SO, I posted my somewhat crude sollution myself. It allows for only one array being passed, and it being the last element of the parameter list. Actually, it is not passing the array at all, but a list of its elements, which are re-assembled into an array by called_function(), but it worked for me. If someone knows a better way, feel free to add it here.

+5  A: 
calling_function()
{
    variable="a"
    array=( "x", "y", "z" )
    called_function "${variable}" "${array[@]}"
}

called_function()
{
    local_variable="${1}"
    shift
    local_array=("${@}")
}

Improved by TheBonsai, thanks.

DevSolar
+1  A: 

Here you have nice reference and tons of examples.

Artem Barger
+4  A: 

DevSolar's answer has one point I don't understand (maybe he has a specific reason to do so, but I can't think of one): He sets the array from the positional parameters element by element, iterative.

An easier approuch would be

called_function()
{
  ...
  # do everything like shown by DevSolar
  ...

  # now get a copy of the positional parameters
  local_array=("$@")
  ...
}
TheBonsai
My reason for not doing so is that I haven't toyed with bash arrays at all until a few days ago. Previously I'd have switched to Perl if it became complex, an option I don't have at my current job. Thanks for the hint!
DevSolar
+1  A: 

this doesnt work if there are spaces in one array element

Timo
And do you have a way to do it that *works* with spaces in array elements? Might be difficult, because AFAIK in bash an array is a list of elements *separated by spaces*...
DevSolar
It does work with spaces. Bash uses strings with line break, arrays and probably more things that shall have the same purpose. I mixed that up.
Timo
In case you need to convert the result of `find` to an array set IFS=$'\n'
Timo
In fact I love bash. It is free.
Timo
+2  A: 

You can pass multiple arrays as arguments using something like this:

takes_ary_as_arg()
{
    declare -a argAry1=("${!1}")
    echo "${argAry1[@]}"

    declare -a argAry2=("${!2}")
    echo "${argAry2[@]}"
}
try_with_local_arys()
{
    # array variables could have local scope
    local descTable=(
        "sli4-iread"
        "sli4-iwrite"
        "sli3-iread"
        "sli3-iwrite"
    )
    local optsTable=(
        "--msix  --iread"
        "--msix  --iwrite"
        "--msi   --iread"
        "--msi   --iwrite"
    )
    takes_ary_as_arg descTable[@] optsTable[@]
}
try_with_local_arys

will echo:

sli4-iread sli4-iwrite sli3-iread sli3-iwrite
--msix --iread --msix --iwrite --msi --iread --msi --iwrite

KenB