在shell脚本中,美元符号后面跟着一个at符号(@)是什么意思?
例如:
umbrella_corp_options $@
在shell脚本中,美元符号后面跟着一个at符号(@)是什么意思?
例如:
umbrella_corp_options $@
当前回答
以下是命令行参数:
$@ =将所有参数存储在string列表中 $* =将所有参数存储为单个字符串 $# =存储参数的数量
其他回答
$@与$*几乎相同,都表示“所有命令行参数”。它们通常用于简单地将所有参数传递给另一个程序(从而形成了对其他程序的包装)。
这两种语法之间的差异体现在你有一个带空格的参数(例如),并把$@放在双引号中:
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
$@基本上用于引用shell-script的所有命令行参数。 $1, $2, $3是第一个命令行参数,第二个命令行参数,第三个参数。
的意思。
简而言之,$@扩展为从调用者传递给函数或脚本的参数。它的含义与上下文相关:在函数内部,它扩展为传递给该函数的参数。如果在脚本中使用(在函数之外),则扩展为传递给该脚本的参数。
$ cat my-script
#! /bin/sh
echo "$@"
$ ./my-script "Hi!"
Hi!
$ put () { echo "$@"; }
$ put "Hi!"
Hi!
*注意:分词。
shell根据IFS环境变量的内容拆分令牌。默认值为\t\n;即,空格、制表符和换行符。展开“$@”可以得到传入参数的原始副本。扩展$@可能不会。更具体地说,任何包含IFS中出现的字符的参数都可能分裂为两个或多个参数或被截断。
因此,大多数时候你想要使用的是“$@”,而不是$@。
纯$@的使用在大多数情况下意味着“尽可能地伤害程序员”,因为在大多数情况下,它会导致单词分离、空格和参数中的其他字符的问题。
在(猜测的)99%的情况下,需要将它括在"中:"$@"是可以用于可靠地遍历参数的。
for a in "$@"; do something_with "$a"; done
摘自手册:
@ 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 beginning 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).