How to expand array in Bash adding double quotes to elements?

772 Views Asked by At

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?

2

There are 2 best solutions below

0
Benjamin W. On BEST ANSWER

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[@]}"
0
markp-fuso On

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"