Passing arrays as parameters in bash

arrays, bash

Solution

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

Edit/notes: (from comments below)

- `descTable` and `optsTable` are passed as names and are expanded in the function. Thus no `$` is needed when given as parameters.

- Note that this still works even with `descTable` etc being defined with `local`, because locals are visible to the functions they call.

- The `!` in `${!1}` expands the arg 1 variable.

- `declare -a` just makes the indexed array explicit, it is not strictly necessary.

Problem

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

Original source

Related problems