为了账号安全,请及时绑定邮箱和手机立即绑定

访问bash命令行args$@vs$*

访问bash命令行args$@vs$*

月关宝盒 2019-07-13 18:53:30
在许多这样的问题和bash教程中,我看到我可以通过两种方式访问bash脚本中的命令行args:$ ~ >cat testargs.sh  #!/bin/bashecho "you passed me" $*echo "you passed me" $@其结果是:$ ~> bash testargs.sh arg1 arg2 you passed me arg1 arg2 you passed me arg1 arg2.之间的区别是什么?$*和$@?何时使用前者,何时使用后者?
查看完整描述

3 回答

?
四季花海

TA贡献1811条经验 获得超5个赞

当引用特殊参数时,会出现差异。让我来说明不同之处:


$ set -- "arg  1" "arg  2" "arg  3"


$ for word in $*; do echo "$word"; done

arg

1

arg

2

arg

3


$ for word in $@; do echo "$word"; done

arg

1

arg

2

arg

3


$ for word in "$*"; do echo "$word"; done

arg  1 arg  2 arg  3


$ for word in "$@"; do echo "$word"; done

arg  1

arg  2

arg  3

关于引用的重要性的另一个例子:注意,在“arg”和数字之间有两个空格,但是如果我不能引用$word:


$ for word in "$@"; do echo $word; done

arg 1

arg 2

arg 3

在巴什,"$@"是要迭代的“默认”列表:


$ for word; do echo "$word"; done

arg  1

arg  2

arg  3


查看完整回答
反对 回复 2019-07-13
?
红颜莎娜

TA贡献1842条经验 获得超12个赞

$*

展开到位置参数,从一个开始。当展开发生在双引号中时,它扩展为一个单词,每个参数的值由IFS特殊变量的第一个字符分隔。也就是说,“$*”等同于“$1c$2c.”,其中c是IFS变量值的第一个字符。如果IFS未设置,则参数由空格分隔。如果IFS为NULL,则将参数连接在一起,而不使用中间分隔符。

$@

展开到位置参数,从一个开始。当展开发生在双引号中时,每个参数展开为一个单独的单词。即“$@”等于“$1”$2“.如果双引号扩展发生在一个单词内,则第一个参数的扩展与原始单词的开头部分连接,而最后一个参数的扩展与原始单词的最后部分连接。当没有位置参数时,“$@”和$@展开为空(即删除它们)。

查看完整回答
反对 回复 2019-07-13
?
慕的地6264312

TA贡献1817条经验 获得超6个赞

这个示例让我们在使用“at”和“Asterix”时突出显示它们之间的区别。我声明了两个数组“水果”和“蔬菜”


fruits=(apple pear plumm peach melon)            

vegetables=(carrot tomato cucumber potatoe onion)


printf "Fruits:\t%s\n" "${fruits[*]}"            

printf "Fruits:\t%s\n" "${fruits[@]}"            

echo + --------------------------------------------- +      

printf "Vegetables:\t%s\n" "${vegetables[*]}"    

printf "Vegetables:\t%s\n" "${vegetables[@]}"    

请参见下面的结果-上面的代码:


Fruits: apple pear plumm peach melon

Fruits: apple

Fruits: pear

Fruits: plumm

Fruits: peach

Fruits: melon

+ --------------------------------------------- +

Vegetables: carrot tomato cucumber potatoe onion

Vegetables: carrot

Vegetables: tomato

Vegetables: cucumber

Vegetables: potatoe

Vegetables: onion


查看完整回答
反对 回复 2019-07-13
  • 3 回答
  • 0 关注
  • 862 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信