Freddie Chopin Freddie Chopin - 1 month ago 14
Bash Question

Passing multiple command arguments in single argument to shell function

I would like to have a function in which I execute command (for example

make
) and one argument of that function can be a string with multiple arguments for that command.

Here's an example of a failing script which demonstrates what I would like to achieve:

#!/bin/sh

set -e
set -u
set -v
set -x
buildSomething() {
make ${1}
}

buildSomething "CFLAGS=\"-DX=1 -DY=1\" CXXFLAGS=\"-DXX=11 -DYY=11\" -j$(nproc)"


This fails because shell decides to quote the arguments again:

buildSomething "CFLAGS=\"-DX=1 -DY=1\" CXXFLAGS=\"-DXX=11 -DYY=11\" -j$(nproc)"
nproc
++ nproc
+ buildSomething 'CFLAGS="-DX=1 -DY=1" CXXFLAGS="-DXX=11 -DYY=11" -j8'
+ make 'CFLAGS="-DX=1' '-DY=1"' 'CXXFLAGS="-DXX=11' '-DYY=11"' -j8
make: invalid option -- 'D'
make: invalid option -- 'Y'
make: invalid option -- '='
make: invalid option -- '1'
make: invalid option -- '"'
make: invalid option -- 'D'
make: invalid option -- 'Y'
make: invalid option -- 'Y'
make: invalid option -- '='
make: invalid option -- '1'
make: invalid option -- '1'
make: invalid option -- '"'


I know that the problem is with quoting, but I think I've tried all combinations that I could think of... Is there any generic solution to this problem? I don't insist on fixing this exact script above, a different approach that would allow me to do the thing mentioned in the first paragraph would also be ok. As such function would have multiple commands, each can have its arguments in a different argument of the function, it's really important for me to have multiple arguments for each command in one function argument (or something equivalent).

Answer
#!/bin/sh

buildSomething() {
    eval "make ${1}"
}

buildSomething 'CFLAGS=\"-DX=1 -DY=1\" CXXFLAGS=\"-DXX=11 -DYY=11\"'" -j$(nproc)"