我已经好几次这样做了,它似乎永远不会正常工作.有谁能解释为什么?
function Foobar
{
cmd -opt1 -opt2 $@
}
Run Code Online (Sandbox Code Playgroud)
这是什么应该做的是让这个电话Foobar做同样的事情与调用cmd,但有一些额外的参数(-opt1和-opt2,在这个例子中).
不幸的是,这不能正常工作.如果所有参数都缺少空格,它就可以了.但是如果你想要一个带空格的参数,你可以用引号写出来,而Bash有助于剥离引号,打破命令.如何防止这种错误行为?
$@在替换参数值之后,你需要加倍引用以防止bash执行不需要的解析步骤(单词拆分等):
function Foobar
{
cmd -opt1 -opt2 "$@"
}
Run Code Online (Sandbox Code Playgroud)
从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).
Run Code Online (Sandbox Code Playgroud)