指点成金-最美分享吧

登录

Shell 数组中的 [@] 和 [*]

佚名 举报

篇首语:本文由小编为大家整理,主要介绍了Shell 数组中的 [@] 和 [*]相关的知识,希望对你有一定的参考价值。


​@​​​ 和 ​​*​​ 为 shell 中对数组使用时的常用特殊字符,用法示例如下:

#!/bin/bash
#数组变量arr1
arr1=(my name is shanhy)

#如下写法表示的是数组的所有元素
#$arr1[@] 或 $arr1[*]

i=0
for v in $arr1[@]
do
echo "item$i>>>$v"
let i++
done

#如下写法表示的是数组的元素个数
#$#arr1[@] 或 $#arr1[*]

echo "数组长度>>>$#arr1[@]"

#如下写法表示第一个元素的长度,即第一个元素的字符个数
#$#arr1 或 $!arr1[0]

echo "数组第一个元素的长度>>>$#arr1"
echo "数组第二个元素的长度>>>$#arr1[1]"

#如下写法表示将数组的序号组装成一个数组,等同于arr1=(0 1 2 3)
#$!arr1[@] 或 $!arr1[*]

echo "数组的序号数组>>>$!arr1[@]"

运行后输出结果如下:

item0>>>my
item1>>>name
item2>>>is
item3>>>shanhy
数组长度>>>4
数组第一个元素的长度>>>2
数组的序号数组>>>0 1 2 3
[root@localhost soft]# ./test.sh
item0>>>my
item1>>>name
item2>>>is
item3>>>shanhy
数组长度>>>4
数组第一个元素的长度>>>2
数组第二个元素的长度>>>4
数组的序号数组>>>0 1 2 3

引用《ABSG》 CHAPTER 27有描述:
As seen in the previous example, either $array_name[@] or $array_name[] refers to all the elements
of the array. Similarly, to get a count of the number of elements in an array, use either $#array_name[@]
or $#array_name[
]. $#array_name is the length (number of characters) of $array_name[0], the first
element of the array.


(END)


以上是关于Shell 数组中的 [@] 和 [*]的主要内容,如果未能解决你的问题,请参考以下文章