加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

linux – $*和$@有什么区别

发布时间:2020-12-13 16:56:49 所属栏目:Linux 来源:网络整理
导读:谁能简单解释一下 $*和$@有什么区别? 为什么上面的内容有两个变量? 解决方法 除了技术文档中描述的差异之外,最好使用一些示例显示: 假设我们有四个shell脚本test1.sh: #!/bin/bashrm $* test2.sh: #!/bin/bashrm "$*" test3.sh: #!/bin/bashrm $@ test
谁能简单解释一下

> $*和$@有什么区别?
>为什么上面的内容有两个变量?

解决方法

除了技术文档中描述的差异之外,最好使用一些示例显示:

假设我们有四个shell脚本test1.sh:

#!/bin/bash
rm $*

test2.sh:

#!/bin/bash
rm "$*"

test3.sh:

#!/bin/bash
rm $@

test4.sh:

#!/bin/bash
rm "$@"

(我在这里使用rm而不是echo,因为有了echo,你看不出差别)

我们使用以下命令行调用所有这些命令行,否则在一个空的目录中:

./testX.sh "Hello World" Foo Bar

对于test1.sh和test3.sh,我们收到以下输出:

rm: cannot remove ‘Hello’: No such file or directory
rm: cannot remove ‘World’: No such file or directory
rm: cannot remove ‘Foo’: No such file or directory
rm: cannot remove ‘Bar’: No such file or directory

这意味着,参数被视为一个完整的字符串,与空格连接,然后作为参数重新分配并传递给命令.将参数转发给另一个命令时,这通常没有用.

使用test2.sh,我们得到:

rm: cannot remove ‘Hello World Foo Bar’: No such file or directory

所以我们和test {1,3} .sh一样,但这次,结果作为一个参数传递.

test4.sh有一些新东西:

rm: cannot remove ‘Hello World’: No such file or directory
rm: cannot remove ‘Foo’: No such file or directory
rm: cannot remove ‘Bar’: No such file or directory

这意味着参数的传递方式与它们传递给脚本的方式相同.将参数传递给其他命令时,这很有用.

区别是微妙的,但是在将参数传递给命令时会咬你,这些命令期望命令行中的某些点以及空间参与游戏时的信息.这实际上是大多数炮弹的许多陷阱之一的一个很好的例子.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读