[英]What does $@ mean in a shell script?
在 shell 脚本中,美元符号后跟 at 符号 ( @
) 是什么意思?
例如:
umbrella_corp_options $@
$@
是传递给脚本的所有参数。
例如,如果您调用./someScript.sh foo bar
那么$@
将等于foo bar
。
如果你这样做:
./someScript.sh foo bar
然后在someScript.sh
参考中:
umbrella_corp_options "$@"
这将被传递给umbrella_corp_options
,每个单独的参数都用双引号括起来,允许从调用者那里获取带有空格的参数并传递它们。
$@
与$*
几乎相同,都表示“所有命令行参数”。 它们通常用于简单地将所有参数传递给另一个程序(从而形成围绕该其他程序的包装器)。
当您有一个带有空格的参数(例如)并将$@
放在双引号中时,两种语法之间的差异就会出现:
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
这些是命令行参数,其中:
$@
= 将所有参数存储在字符串列表中
$*
= 将所有参数存储为单个字符串
$#
= 存储参数的数量
在大多数情况下,纯$@
的使用意味着“尽可能地伤害程序员”,因为在大多数情况下,它会导致单词分隔以及参数中的空格和其他字符出现问题。
在(猜测的)99% 的情况下,需要将其括在"
: "$@"
中可以用来可靠地迭代参数。
for a in "$@"; do something_with "$a"; done
简而言之, $@
扩展为从调用者传递给函数或脚本的参数。 它的含义是上下文相关的:在函数内部,它扩展为传递给该函数的参数。 如果在脚本(函数外部)中使用,它会扩展为传递给此类脚本的参数。
$ cat my-script
#! /bin/sh
echo "$@"
$ ./my-script "Hi!"
Hi!
$ put () { echo "$@"; }
$ put "Hi!"
Hi!
* 注:分词。
Shell 根据IFS
环境变量的内容拆分令牌。 它的默认值为\t\n
; 即,空格、制表符和换行符。 扩展"$@"
为您提供传递参数的原始副本。 扩展$@
可能不会。 更具体地说,包含IFS
中存在的字符的任何参数都可能拆分为两个或多个参数或被截断。
因此,大多数时候您想要使用的是"$@"
,而不是$@
。
@
扩展到位置参数,从一个开始。 当扩展出现在双引号内时,每个参数都扩展为一个单独的单词。 即“$@”等价于“$1”“$2”……。如果双引号扩展出现在一个单词中,第一个参数的扩展与原单词的开头部分连接,并且最后一个参数的扩展与原始单词的最后一部分相连。 当没有位置参数时,"$@" 和 $@ 扩展为空(即,它们被删除)。
“传递给函数的所有参数”一开始就让我很头疼。
它不包括$ 0,这是通过脚本(是吗?)到程序的名字,虽然含蓄。
$@
基本上用于引用 shell-script 的所有命令行参数。 $1 , $2 , $3
指的是第一个命令行参数,第二个命令行参数,第三个参数。
它们通常用于简单地将所有 arguments 传递给另一个程序
[root@node1 shell]#./my-script hi 11 33 hi 11 33 [root@node1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.