Reputation: 62818
I've done this several times, and it never seems to work properly. Can anyone explain why?
function Foobar
{
cmd -opt1 -opt2 $@
}
What this is supposed to do is make it so that calling Foobar
does the same thing as calling cmd
, but with a few extra parameters (-opt1
and -opt2
, in this example).
Unfortunately, this doesn't work properly. It works OK if all your arguments lack spaces. But if you want an argument with spaces, you write it in quotes, and Bash helpfully strips away the quotes, breaking the command. How do I prevent this incorrect behavior?
Upvotes: 2
Views: 110
Reputation: 125798
You need to double-quote the $@
to keep bash from performing the unwanted parsing steps (word splitting etc) after substituting the argument values:
function Foobar
{
cmd -opt1 -opt2 "$@"
}
EDIT from the Special Parameters section of the bash manpage:
@ Expands to the positional parameters, starting from one. When
the expansion occurs within double quotes, each parameter
expands to a separate word. That is, "$@" is equivalent to "$1"
"$2" ... If the double-quoted expansion occurs within a word,
the expansion of the first parameter is joined with the begin-
ning part of the original word, and the expansion of the last
parameter is joined with the last part of the original word.
When there are no positional parameters, "$@" and $@ expand to
nothing (i.e., they are removed).
Upvotes: 8