This question already has an answer here:
这个问题在这里已有答案:
- What's the difference between $@ and $* in UNIX? 4 answers
UNIX中$ @和$ *的区别是什么? 4个答案
I always use $@
when I want all arguments of bash function but recently I just found that $*
also works in the same way, and it also can use as array index.
当我想要bash函数的所有参数时,我总是使用$ @但最近我发现$ *也以相同的方式工作,它也可以用作数组索引。
My question is What is difference between $*
an $@
in Bash? and which one should I prefer?
我的问题是Bash中$ *和$ @之间的区别是什么?我应该选择哪一个?
2 个解决方案
#1
8
The Bash manual is quite clear on this topic:
Bash手册对此主题非常清楚:
$*
All of the positional parameters, seen as a single word.
所有的位置参数,看作一个单词。
Note:
$*
must be quoted.注意:必须引用$ *。
$@
Same as
$*
, but each parameter is a quoted string, that is, the parameters are passed on intact, without interpretation or expansion. This means, among other things, that each parameter in the argument list is seen as a separate word.与$ *相同,但每个参数都是带引号的字符串,即参数完整传递,无需解释或扩展。这意味着,参数列表中的每个参数都被视为一个单独的单词。
Note: Of course,
$@
should be quoted.注意:当然,应该引用$ @。
#2
2
There is a historical development here. $*
was found to be insufficient, and so $@
was introduced to replace it. There are still situations where $*
is useful; but unless you specifically want to break up quoted tokens, you should avoid it.
这里有一个历史发展。发现$ *不足,因此引入$ @来替换它。仍然存在$ *有用的情况;但除非你特别想要打破引用的代币,否则你应该避免它。
#1
8
The Bash manual is quite clear on this topic:
Bash手册对此主题非常清楚:
$*
All of the positional parameters, seen as a single word.
所有的位置参数,看作一个单词。
Note:
$*
must be quoted.注意:必须引用$ *。
$@
Same as
$*
, but each parameter is a quoted string, that is, the parameters are passed on intact, without interpretation or expansion. This means, among other things, that each parameter in the argument list is seen as a separate word.与$ *相同,但每个参数都是带引号的字符串,即参数完整传递,无需解释或扩展。这意味着,参数列表中的每个参数都被视为一个单独的单词。
Note: Of course,
$@
should be quoted.注意:当然,应该引用$ @。
#2
2
There is a historical development here. $*
was found to be insufficient, and so $@
was introduced to replace it. There are still situations where $*
is useful; but unless you specifically want to break up quoted tokens, you should avoid it.
这里有一个历史发展。发现$ *不足,因此引入$ @来替换它。仍然存在$ *有用的情况;但除非你特别想要打破引用的代币,否则你应该避免它。