Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass array literal to a bash function

First I've read about passing arrays in general -- all examples I saw first created temporary variable for array and then passed it. Taken from https://stackoverflow.com/a/26443029/210342

show_value () # array index
{
    local -n myarray=$1
    local idx=$2
    echo "${myarray[$idx]}"
}

shadock=(ga bu zo meu)
show_value shadock 2

Is there a way to pass array directly as literal, i.e. without creating temporary variable?

I tried naive approach simply substituting the name with data, but I syntax error on "(".

Update:

I use openSUSE Leap 15.3 with bash 4.4. The above code of course works, but I would like to change the call into:

show_value (ga bu zo meu) 2

i.e. pass array data directly (without using extra variable).

like image 704
greenoldman Avatar asked Jul 14 '26 22:07

greenoldman


1 Answers

If you want to change the order of the arguments:

show_value () #  index array_element [...]
{
    local idx=$1
    local -a myarray=("${@:2}")
    echo "${myarray[$idx]}"
}

then

shadock=(ga bu zo meu)
show_value 2 "${shadock[@]}"   # => zo

If you want to keep the index as the last argument, then

show_value () #  array_element [...] index
{
    local -a myarray=("${@:1:$#-1}")
    local idx=${!#}
    echo "${myarray[$idx]}"
}
show_value "${shadock[@]}" 2   # => zo

local -n myarray=$1 is certainly much tidier than all that, isn't it? It will also be faster and more memory efficient -- you don't have to copy all the data.

like image 86
glenn jackman Avatar answered Jul 16 '26 14:07

glenn jackman