-2

I would like to pass an array to a function and use the values in the array as a command parameter, something like this:

command can receive N parameters, example: param1 param2 oneparam 1 a 2 b 3 c onotherparam

my_func() {
    command param1 param2 $1 $2 $3
}

my_arr=("1 a" "2 b" "3 c")

my_func "oneparam" ${my_arr[@]} "onotherparam"

But I don't receive it all as a single parameter in the function, so $1 is only 1 a instead of "1 a" "2 b" "3 c"

Then I though I can do this:

my_func() {
    command param1 param2 $1 $2 $3
}

my_arr=("1 a" "2 b" "3 c")
params=${my_arr[@]/%/\"}  # 1 a" 2 b" 3 c"

my_func "oneparam" "$params" "onotherparam"

But it only places the quotes at the end of each element.

How can I place quotes on both sides of each array element?

user5507535
  • 1,580
  • 1
  • 18
  • 39
  • Should `command` get three parameters, `par1`, `par2`, and `1 a 2 b 3 c`, or 5, as in `par1`, `par2`, `1 a`, `2 b`, `3 c`? – Benjamin W. Nov 08 '20 at 20:21
  • @BenjaminW. It's 5 parameters in total. – user5507535 Nov 08 '20 at 20:28
  • It is unclear what you are trying to do here. A visit to shellcheck.net will point out numerous quoting issues. But you function is not clear whether you are expecting all the elements of `my_arr` or only one of them. As written, you will only get one word split argument. – dawg Nov 08 '20 at 20:29
  • What are `par1` and `par2`? – dawg Nov 08 '20 at 20:31

2 Answers2

1

To preserve the parameters with proper quoting, you have to make two changes: quote the array expansion and use all parameters in the function instead of just $1.

my_func() {
    command par1 par2 "$@"
}

my_arr=("1 a" "2 b" "3 c")

my_func "${my_arr[@]}"
Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
0

If the OP really wants to maintain a set of double quotes around the 3 array elements then one idea would be to explicitly add them when populating the array, eg:

my_arr=('"1 a"' '"2 b"' '"3 c"')

Using a slightly modified OPs function definition:

my_func() {
    echo command param1 param2 $1 $2 $3
}

And turning on debug:

set -xv

We see the following when calling the function (notice the calls with and without quotes around the array reference):

$ my_func ${my_arr[@]}
my_func ${my_arr[@]}
+ my_func '"1' 'a"' '"2' 'b"' '"3' 'c"'
+ echo param1 param2 '"1' 'a"' '"2'
param1 param2 "1 a" "2

# and

$ my_func "${my_arr[@]}"
my_func "${my_arr[@]}"
+ my_func '"1 a"' '"2 b"' '"3 c"'
+ echo param1 param2 '"1' 'a"' '"2' 'b"' '"3' 'c"'
param1 param2 "1 a" "2 b" "3 c"
markp-fuso
  • 28,790
  • 4
  • 16
  • 36