免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3427 | 回复: 2
打印 上一主题 下一主题

请教shell编程中$*和$@以及数组中*和@的区别? 谢谢. [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2007-03-16 11:21 |只看该作者 |倒序浏览
看到<sams Teach yourself shell programming in 24 hours>里面关于参数章节的对$*和$@的解释如下
$*: All the arguments are double quoted. If a script receives two arguments, $* is equivalent to $1 $2.
$@: All the arguments are individually double quoted. If a script receives two arguments, $@ is equivalent to $1 $2

还有一段对$*的理解说明:
The main difference between these two is how they expand arguments. When $* is used, it simply expands each argument without preserving quoting. This can sometimes cause a problem. If your script is given a filename containing spaces as an argument,

mytar –t "my tar file.tar"

using $* would mean that the for loop would call tar three times for files named my, tar, and file.tar, instead of once for the file you requested: my tar file.tar.

By using $@, you avoid this problem because it expands each argument as it was quoted on the command line.


我的理解为按照mytar "my tar file.tar"的格式
使用$*将去掉参数中""的作用, 而把参数作为三个值, 而使用$@则保留""的作用, 将参数看作一个值.
我使用如下的例子验证
echo 'difference between $* and $@'
for FRUIT in $*
do
    echo $FRUIT
done
for P in $@
do
    echo $P
done
其运行结果是一样的.  

是不是我的理解错了. 哪位仁兄帮忙解释一下. 另外, shell中对数组的引用也有*和@的区别. 是否和这个也一样?

我的环境是 Fedora core 1,
#bash --version
GNU bash, version 2.05b.0(1)-release (i386-redhat-linux-gnu)
Copyright (C) 2002 Free Software Foundation, Inc.

论坛徽章:
0
2 [报告]
发表于 2007-04-18 13:12 |只看该作者
写了这么一大篇 得顶一下

论坛徽章:
0
3 [报告]
发表于 2007-04-25 17:21 |只看该作者
嘿嘿,我新手
#mytar.sh
echo number of auguments is $#
for var in $*
do echo $var
done

$./mytar.sh a b c
$number of auguments is 3
$a
$b
$c

$./mytar.sh 'a b' c
#number of auguments is 2
$a
$b
$c

#mytar2.sh
echo number of auguments is $#
for var in "$*"
do echo $var
done

$./mytar.sh2 'a b' c
#number of auguments is 2
$a b c

#mytar3.sh
echo number of auguments is $#
for var in "$@"
do echo $var
done

$./mytar.sh3 'a b' c
#number of auguments is 2
$a b
$c

#mytar4.sh
echo number of auguments is $#
for var in $@
do echo $var
done

$./mytar.sh4 'a b' c
#number of auguments is 2
$a
$b
$c

感觉区别就在有没有”“的时候才能体会的到,这是我的理解

[ 本帖最后由 kedechuan 于 2007-4-25 17:35 编辑 ]
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP