bash shell 脚本中的 $@ 和 $* 有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15596826/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 04:58:05  来源:igfitidea点击:

What is the difference between $@ and $* in shell script?

linuxbashshell

提问by 0x90

in my script.sh:

在我的script.sh

aa=$@
bb=$*
echo $aa
echo $bb

when running it:

运行时:

 source script.sh a b c d e f g

I get:

我得到:

a b c d e f g
a b c d e f g

What is the difference between $@and $*?

$@和 和有什么不一样$*

回答by Igor Chubin

There are no difference between $*and $@, but there is a difference between "$@"and "$*".

有没有什么区别$*$@,但之间的差异"$@""$*"

$ cat 1.sh
mkdir "$*"

$ cat 2.sh
mkdir "$@"

$ sh 1.sh a "b c" d

$ ls -l
total 12
-rw-r--r-- 1 igor igor   11 mar 24 10:20 1.sh
-rw-r--r-- 1 igor igor   11 mar 24 10:20 2.sh
drwxr-xr-x 2 igor igor 4096 mar 24 10:21 a b c d

We gave three arguments to the script (a, b cand d) but in "$*" they all were merged into one argument a b c d.

我们为脚本提供了三个参数(a,b cd),但在“$*”中,它们都合并为一个参数a b c d

$ sh 2.sh a "b c" d

$ ls -l
total 24
-rw-r--r-- 1 igor igor   11 mar 24 10:20 1.sh
-rw-r--r-- 1 igor igor   11 mar 24 10:20 2.sh
drwxr-xr-x 2 igor igor 4096 mar 24 10:21 a
drwxr-xr-x 2 igor igor 4096 mar 24 10:21 a b c d
drwxr-xr-x 2 igor igor 4096 mar 24 10:21 b c
drwxr-xr-x 2 igor igor 4096 mar 24 10:21 d

You can see here, that "$*"means always one single argument, and "$@"contains as many arguments, as the script had. "$@" is a special token which means "wrap each individual argument in quotes". So a "b c" dbecomes (or rather stays) "a" "b c" "d"instead of "a b c d"("$*") or "a" "b" "c" "d"($@or $*).

您可以在这里看到,这"$*"意味着始终只有一个参数,并且"$@"包含与脚本一样多的参数。"$@" 是一个特殊标记,意思是“将每个单独的参数用引号括起来”。所以a "b c" d变成(或更确切地说保持)"a" "b c" "d"而不是"a b c d""$*")或"a" "b" "c" "d"$@$*)。

Also, I would recommend this beautiful reading on the theme:

另外,我会推荐这个关于这个主题的美丽读物:

http://tldp.org/LDP/abs/html/internalvariables.html#ARGLIST

http://tldp.org/LDP/abs/html/internalvariables.html#ARGLIST