0

My problem is not simple passing parameters with spaces (I know how to achieve that), consider more complicated case:

function build() {
  make CC="$1" CFLAGS="$2" $* # $* is not correct here!
}

build gcc "XXX" VAR1="a b" VAR2="c=A d=B" LDFLAGS="-L/opt/lib -lm"

as equivalent to

make CC=gcc CFLAGS=XXX VAR1="a b" VAR2="c=A d=B" LDFLAGS="-L/opt/lib -lm"

I would like to achieve this one to work in shell (portable solutions please, no bashisms, etc). Any suggestions, recommendations?

  • And, why aren't you using "$@" which is designed exactly for this purpose? – MAP Jul 6 '16 at 1:27
  • 1
    Forget about $* and remember "$@" instead. "$@" is very often useful whereas "$*" is very rarely useful and the unquoted forms are even rarer. – Gilles Jul 6 '16 at 23:09
2

There are two elements to a better solution:

  • shift
  • (more) quoting

Define the function using shift, like this:

function build {
  local cc="$1"
  local cflags="$2"
  shift 2
  make CC="$cc" CFLAGS="$cflags" "$@"
}

where we save the first two parameters to local variables, then shift the whole argument array by two; also, quote the "$@" expansion.

Then, call it with extra quoting, like this:

build gcc "XXX" 'VAR1="a b" VAR2="c=A d=B"' 'LDFLAGS="-L/opt/lib -lm"'

where the single quotes protect the extra arguments into the function; otherwise, the shell removes the quotes and you'd be left with VAR2=c=A d=B (unquoted) in the function.

  • 1
    He probably wants "$@", not "$*". – PSkocik Jul 5 '16 at 17:44
  • Thanks, man! I mistakenly quoted arguments (yes, I played with "$@") like VAR2='"c=A d=B"'. I will check a bit later today and mark answer. Btw, shouldn't your example contain couple more single quotes? – 0andriy Jul 6 '16 at 8:29
  • That's not fully correct due to inheritance of the double quotes to the later parameters, means that argument of VAR2 becomes "c=A d=B" instead of c=A d=B in the internals of Makefile, for now it still works when I dropped double quotes in the quoting, i.e. 'VAR2=c=A d=B'. – 0andriy Jul 6 '16 at 12:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.