linuxbashfunctionshellvariable-substitution

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


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?


Solution

  • 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[@]}"