是什么在shell脚本$ @ $和*之间的区别? [英] What is the difference between $@ and $* in shell script?
问题描述
在我的 script.sh
:
aa=$@
bb=$*
echo $aa
echo $bb
运行时:
source script.sh a b c d e f g
我得到:
a b c d e f g
a b c d e f g
是什么区别 $ @
和 $ *
?
推荐答案
有 $ *
和 $ @ $ C之间没有差异$ C>,但
$ @
和$ *
。
$ 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
我们给了三个参数的脚本( A
, BC
和 D
),但在$ *他们都被合并为一个参数 ABCD
。
We gave three arguments to the script (a
, b c
and d
) but in "$*" they all were merged into one argument 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
您可以在这里看到,该$ *
表示总是一个单一的参数,而$ @
包含许多参数,如脚本了。 $ @是一个特殊的记号,这意味着包装各个论点引号。因此, ABCD
成为(或者说保持)一,BC,D
而不是ABCD
($ *
)或AbC 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" d
becomes (or rather stays) "a" "b c" "d"
instead of "a b c d"
("$*"
) or "a" "b" "c" "d"
($@
or $*
).
另外,我建议的主题是这个美丽阅读:
Also, I would recommend this beautiful reading on the theme:
http://tldp.org/LDP/abs/html/internalvariables。 HTML#ARGLIST
这篇关于是什么在shell脚本$ @ $和*之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!