Shell脚本 数组

版权声明:转载或者应用请注明出处 https://blog.csdn.net/qq_35180983/article/details/82501806

bash支持一维数组(不支持多维数组),并且没有限定数组的大小。

类似与C语言,数组元素的下标由0开始编号,获取数组中的元素要利用下标,下标可以是整数或算术表达式,其值应大于或等于0。

1、定义数组

在Shell中,用括号来表示数组,数组元素用"空格"符号分割开。

  • 定义数组的一般形式为:数组名=(值1 值2 ... 值n)

例如:

array_name=(value0 value1 value2 value3)

或者

array_name=(

value0

value1

value2

value3

)

还可以单独定义数组的各个分量:

array_name[0]=value0

array_name[1]=value1

array_name[n]=valuen

可以不使用连续的下标,而且下标的范围没有限制。

#!/bin/bash
array1=(1 2 3 7 9)

array2=(
54
76
)

array3[0]=98
array3[5]=100

2、读取数组

  • 读取数组元素值的一般格式是:${数组名[下标]}

注意:没有也不会报数组越界异常,就是查询不出来

例如:

valuen=${array_name[n]}

使用@或者*符号可以获取数组中的所有元素,例如:

echo ${array_name[@]}

[root@hadoop01 shell]# vi array.sh
#!/bin/bash

array1=(1 2 3 7 9)

array2=(
11
33
54
76
)

array1[0]=111
array2[1]=222

array3[0]=98
array3[5]=100

echo "this is array1"
echo ${array1}
echo ${array1[0]}
echo ${array1[@]}
echo ${array1[*]}

echo "this is array2"
echo ${array2}
echo ${array2[1]}
echo ${array2[@]}
echo ${array2[*]}

echo "this is array3"
echo ${array3}
echo ${array3[1]}
echo ${array3[@]}
echo ${array3[*]}

[root@hadoop01 shell]# chmod a+x array.sh 
[root@hadoop01 shell]# ./array.sh 
this is array1
111
111
111 2 3 7 9
111 2 3 7 9
this is array2
11
222
11 222 54 76
11 222 54 76
this is array3
98

98 100
98 100
[root@hadoop01 shell]# 

3、获取数组的长度

获取数组长度的方法与获取字符串长度的方法相同,例如:

# 取得数组元素的个数

length=${#array_name[@]}

# 或者

length=${#array_name[*]}

echo "-----length-----"
echo ${#array1[*]}
echo ${#array2[*]}
echo ${#array3[*]}


-----length-----
5
4
2

4、取得数组单个元素的长度

lengthn=${#array_name[n]}

echo "---single length---"
echo ${#array1[0]}
echo ${#array2[1]}
echo ${#array3[5]}

---single length---
3
3
3

完整练习代码:(注意在运行方式)

[root@hadoop01 shell]# vi array.sh

#!/bin/bash

array1=(1 2 3 7 9)

array2=(
11
33
54
76
)

array1[0]=111
array2[1]=222

array3[0]=98
array3[5]=100

echo "this is array1"
echo ${array1}
echo ${array1[0]}
echo ${array1[@]}
echo ${array1[*]}

echo "this is array2"
echo ${array2}
echo ${array2[1]}
echo ${array2[@]}
echo ${array2[*]}

echo "this is array3"
echo ${array3}
echo ${array3[1]}
echo ${array3[@]}
echo ${array3[*]}

echo "-----length-----"
echo ${#array1[*]}
echo ${#array2[*]}
echo ${#array3[*]}

echo "---single length---"
echo ${#array1[0]}
echo ${#array2[1]}
echo ${#array3[5]}

[root@hadoop01 shell]# ./array.sh 
this is array1
111
111
111 2 3 7 9
111 2 3 7 9
this is array2
11
222
11 222 54 76
11 222 54 76
this is array3
98

98 100
98 100
-----length-----
5
4
2
---single length---
3
3
3

猜你喜欢

转载自blog.csdn.net/qq_35180983/article/details/82501806