tru*_*ktr 155 unix linux bash shell sh
@
在shell脚本中,一个美元符号后跟一个at符号()意味着什么?
例如:
umbrella_corp_options $@
Run Code Online (Sandbox Code Playgroud)
Har*_*Har 208
$@
是传递给脚本的所有参数.
例如,如果你打电话./someScript.sh foo bar
那么$@
就等于foo bar
.
如果你这样做:
./someScript.sh foo bar
Run Code Online (Sandbox Code Playgroud)
然后在内部someScript.sh
参考:
umbrella_corp_options "$@"
Run Code Online (Sandbox Code Playgroud)
这将被传递给umbrella_corp_options
每个单独的参数用双引号括起来,允许从调用者获取带有空格的参数并传递它们.
Alf*_*lfe 89
$@
几乎相同$*
,都意味着"所有命令行参数".它们通常用于简单地将所有参数传递给另一个程序(从而形成围绕其他程序的包装).
当你有一个带有空格的参数(例如)并放入$@
双引号时,两个语法之间的差异会显示出来:
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.
Run Code Online (Sandbox Code Playgroud)
示例:致电
wrapper "one two three" four five "six seven"
Run Code Online (Sandbox Code Playgroud)
将导致:
"$@": 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
Run Code Online (Sandbox Code Playgroud)
Lui*_*ire 19
简而言之,$@
扩展为从调用者传递到函数或脚本的参数。它的含义与上下文相关:在函数内部,它扩展为传递给该函数的参数。如果在脚本中(在函数外部)使用,它会扩展为传递给该脚本的参数。
$ cat my-script
#! /bin/sh
echo "$@"
$ ./my-script "Hi!"
Hi!
Run Code Online (Sandbox Code Playgroud)
$ put () { echo "$@"; }
$ put "Hi!"
Hi!
Run Code Online (Sandbox Code Playgroud)
* 注意:分词。
shell 根据IFS
环境变量的内容分割令牌。它的默认值是 \t\n
;即空白、制表符和换行符。扩展"$@"
为您提供了所传递参数的原始副本。扩大$@
也许不行。更具体地说,任何包含 中 存在的字符的参数IFS
可能会分成两个或多个参数或被截断。
因此,大多数时候您想要使用的是"$@"
,而不是$@
。
glg*_*lgl 11
$@
在大多数情况下,使用纯手段"尽可能地伤害程序员",因为在大多数情况下,它会导致单词分离以及参数中的空格和其他字符的问题.
在(猜测)99%的所有情况中,需要将其包含在"
:"$@"
可用于可靠地迭代参数的内容.
for a in "$@"; do something_with "$a"; done
Run Code Online (Sandbox Code Playgroud)