Linux 系统中 $* 和 $@的区别和联系

 

001、两者都可以表示shell脚本的所有参数,两者没有差异(不管是否增加双引号)

 

举例:

a、不加双引号

复制代码
[root@PC1 test1]# ls                                      ## 准备了两个测试脚本
a.sh  b.sh
[root@PC1 test1]# cat a.sh                                ## a.sh的内容如下
#!/bin/bash

echo $*
[root@PC1 test1]# cat b.sh                                ## b.sh的内容如下
#!/bin/bash

echo $@
[root@PC1 test1]# bash a.sh one two three                ## 执行a.sh,同时给脚本a.sh传递3个参数
one two three
[root@PC1 test1]# bash b.sh one two three                ## 执行b.sh,同时给脚本b.sh传递3个参数
one two three
复制代码

 

b、增加双引号

复制代码
[root@PC1 test1]# ls                                  ## 两个测试脚本中都增加了双引号
a.sh  b.sh
[root@PC1 test1]# cat a.sh                
#!/bin/bash

echo "$*"
[root@PC1 test1]# cat b.sh
#!/bin/bash

echo "$@"
[root@PC1 test1]# bash a.sh one two three             ## 结果显示两者没有差异
one two three
[root@PC1 test1]# bash b.sh one two three
one two three
复制代码

 

 

002、把$*和$@放入循环中,两者体现出差异(当使用双引号是两者有差异,不试用双引号时两者无差异)

 

a、不使用双引号

复制代码
[root@PC1 test1]# ls                              ## 准备两个测试程序
a.sh  b.sh
[root@PC1 test1]# cat a.sh                        ## a.sh, $*不加双引号
#!/bin/bash

for i in $*
do
        echo $i
done
[root@PC1 test1]# cat b.sh                        ## b.sh, $@不加双引号
#!/bin/bash

for i in $@
do
        echo $i
done
[root@PC1 test1]# bash a.sh one two three          ## 两者无差异
one
two
three
[root@PC1 test1]# bash b.sh one two three          ## 两者无差异
one
two
three
复制代码

 

b、使用双引号,两者出现差异

复制代码
[root@PC1 test1]# ls
a.sh  b.sh
[root@PC1 test1]# cat a.sh              ## $*放入循环中,且使用双引号
#!/bin/bash

for i in "$*"
do
        echo $i
done
[root@PC1 test1]# cat b.sh             ## $@放入循环中,且使用双引号
#!/bin/bash

for i in "$@"
do
        echo $i
done
[root@PC1 test1]# bash a.sh one two three       ## 两者出现差异,其中 $*, 没有输出换行符, 也就是$i一次性输出了所有的参数, 是一个整体
one two three
[root@PC1 test1]# bash b.sh one two three       ## 两者出现差异, $@不是一个整体,仍然可以作为可迭代对象
one
two
three
复制代码

 

 

003、两者出现的差异有何用途?

 

还不知道

 

posted @   小鲨鱼2018  阅读(843)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
历史上的今天:
2023-01-21 利用 UltraISO 制作linux U盘的启动盘
2023-01-21 windows中如何关闭 BitLocker
2023-01-21 syslinux引导扇区不支持NTFS文件系统
2023-01-21 找到多余1个分区
2023-01-21 ubuntu 中 putty登录 No supported authentication methods available
2023-01-21 sshd: no hostkeys available -- exiting. [fail]
2023-01-21 ubuntu 中 如何查看是否安装了ssh服务、服务状态
点击右上角即可分享
微信分享提示