2013-07-14 215 views
2

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

function Foobar 
{ 
    cmd -opt1 -opt2 [email protected] 
} 

这是什么应该要做的就是让这个调用Foobar做同样的事情与调用cmd,但有一些额外的参数(-opt1-opt2,在这个例子中)。

不幸的是,这不能正常工作。如果你所有的参数都没有空格,它就可以运行但是如果你想要一个带空格的参数,你可以用引号将它写出来,而Bash可以有用地去除引号,打破命令。我如何防止这种不正确的行为?

+0

@ isaach1000这不相关,因为'$ @'不是用户定义的变量名 - 它是POSIX指定的名称,用于访问当前脚本或函数的参数列表。 –

回答

8

你需要双引号的[email protected]保持庆典从替换参数值后进行不必要的解析步骤(分词等):

function Foobar 
{ 
    cmd -opt1 -opt2 "[email protected]" 
} 

从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, "[email protected]" 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, "[email protected]" and [email protected] expand to 
    nothing (i.e., they are removed). 
+0

这不仅仅是展开'$ @',然后把它的所有内容当作一个单词吗? – MathematicalOrchid

+1

不,'$ @'在这方面被特别对待。 –

+0

...好的...任意的特殊规则FTW! : -/ – MathematicalOrchid