2

我已经这样做了好几次,但它似乎永远无法正常工作。谁能解释为什么?

function Foobar
{
  cmd -opt1 -opt2 $@
}

应该做的是让 call 与 callFoobar做同样的事情cmd,但有一些额外的参数(-opt1-opt2,在这个例子中)。

不幸的是,这不能正常工作。如果您的所有论点都缺少空格,则它可以正常工作。但是如果你想要一个带空格的参数,你可以把它写在引号中,然后 Bash 会帮助你去掉引号,从而破坏命令。如何防止这种不正确的行为?

4

1 回答 1

8

在替换参数值后,您需要双引号$@以防止 bash 执行不需要的解析步骤(分词等):

function Foobar
{
  cmd -opt1 -opt2 "$@"
}

从 bash 手册页的特殊参数部分编辑:

@   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).
于 2013-07-14T15:08:49.627 回答