3 回答
TA贡献1993条经验 获得超5个赞
$@与几乎相同$*,均表示“所有命令行参数”。它们通常用于简单地将所有参数传递给另一个程序(从而形成对该另一个程序的包装)。
当您的参数中带有空格(例如)并$@用双引号引起来时,两种语法之间的差异就会显现出来:
wrappedProgram "$@"
# ^^^ this is correct and will hand over all arguments in the way
# we received them, i. e. as several arguments, each of them
# containing all the spaces and other uglinesses they have.
wrappedProgram "$*"
# ^^^ this will hand over exactly one argument, containing all
# original arguments, separated by single spaces.
wrappedProgram $*
# ^^^ this will join all arguments by single spaces as well and
# will then split the string as the shell does on the command
# line, thus it will split an argument containing spaces into
# several arguments.
示例:呼叫
wrapper "one two three" four five "six seven"
将导致:
"$@": wrappedProgram "one two three" four five "six seven"
"$*": wrappedProgram "one two three four five six seven"
^^^^ These spaces are part of the first
argument and are not changed.
$*: wrappedProgram one two three four five six seven
TA贡献1859条经验 获得超6个赞
$@在大多数情况下,使用纯手段“会尽最大努力伤害程序员”,因为在大多数情况下,这会导致单词分隔以及参数中的空格和其他字符出现问题。
在(被猜测的)所有情况的99%中,要求将其括在":"$@"是可用于可靠地遍历参数的内容。
for a in "$@"; do something_with "$a"; done
- 3 回答
- 0 关注
- 3883 浏览
添加回答
举报