0

given array arr and string str . If I send them to function in the next way:

func "${arr[@]}" ${str}

How can I define the array and the string in func function?

function func {
local arr=....
local str=....
}

according to what I understood (It's correct?) if I will do: local arr=("$@") I will get that:
arr[0]=the first argument - in this case it's will be all the array
arr[1]=str

(according to my checks local arr=("$@") gives array exactly like arr (what that I sent) , apart of it's adds str as a last element in this array..)

[I don't ask for "how to send array in bash", but, how can I choose the array from all the arguments]

  • Do you have to use that order? Using `func "$str" "${arr[@]}"` would make things easier. – Socowi Mar 05 '18 at 19:33
  • @Socowi I know, in this way you can skip about the first element. But I want to know how can I deal with the case I brought? –  Mar 05 '18 at 19:34
  • Possible duplicate of [Passing arrays as parameters in bash](https://stackoverflow.com/questions/1063347/passing-arrays-as-parameters-in-bash) – Benjamin W. Mar 05 '18 at 19:57
  • 1
    There are no array values in `bash`. You are passing all the *elements* of the array as separate arguments, not the array itself. – chepner Mar 05 '18 at 21:23

1 Answers1

1

$@ are all the parameters passed to the function. Retrieving the last parameter is easy. Just use the last array entry. Afterwards you have to delete the last entry from the array.

function func {
    local arr=("$@")
    local str="${arr[-1]}"
    unset 'arr[-1]'
}

Make sure to always call func with at least one parameter or the script will fail.

Socowi
  • 25,550
  • 3
  • 32
  • 54
  • Why "-1" ? it's not need to be `"${arr[$((${#arr[@]} - 1))]}"`? –  Mar 05 '18 at 19:49
  • 1
    Newer versions of bash allow negative indices. -1 is the last array entry, -2 the second last array entry, and so on. – Socowi Mar 05 '18 at 19:51