Linux 中数组的应用
001、 创建数组
a、
declare -a array1

。
b、
array1[0]=100

。
002、删除数组
unset array1

。
003、查看数组
a、查看数组所有的元素:
[root@PC1 test]# array1[0]=100 [root@PC1 test]# array1[1]="aaa" [root@PC1 test]# array1[2]="ddd" [root@PC1 test]# echo ${array1[*]} ## 查看数组的所有元素 100 aaa ddd [root@PC1 test]# echo ${array1[@]} 100 aaa ddd

b、查看数组的任意一个元素
[root@PC1 test]# echo ${array1[*]}
100 aaa ddd
[root@PC1 test]# echo ${array1[0]} ## 查看数组的任意一个元素
100
[root@PC1 test]# echo ${array1[2]}
ddd

。
003、遍历数组
[root@PC1 test]# ls [root@PC1 test]# echo ${array1[*]} 100 aaa kkk [root@PC1 test]# echo ${!array1[*]} 0 1 2 [root@PC1 test]# for i in ${array1[*]}; do echo $i; done ## 对数组的元素直接遍历 100 aaa kkk [root@PC1 test]# for i in ${!array1[*]}; do echo ${array1[$i]}; done ## 对数组的索引值进行遍历 100 aaa kkk

004、数组元素的赋值
a、
[root@PC1 test]# declare -a array1 [root@PC1 test]# array1[0]=100 ## 数组元素的赋值 [root@PC1 test]# array1[1]=800 [root@PC1 test]# array1[2]="kkk" [root@PC1 test]# echo ${array1[*]} 100 800 kkk

。
b、
[root@PC1 test]# declare -a array1 [root@PC1 test]# array1=(100 "aaa" "kkk") ## 数组元素的赋值 [root@PC1 test]# echo ${array1[*]} 100 aaa kkk

c、
[root@PC1 test]# declare -a array1 [root@PC1 test]# array1=([0]="aaa" [1]=300 [2]="kkk") [root@PC1 test]# echo ${array1[*]} aaa 300 kkk

。
005、数组元素的追加和更新
a、追加
[root@PC1 test]# declare -a array1 [root@PC1 test]# array1[0]=100 [root@PC1 test]# array1[1]=800 [root@PC1 test]# array1+=("aaa") ## 数组元素的追加 [root@PC1 test]# echo ${array1[*]} 100 800 aaa [root@PC1 test]# array1+=("xxx" "yyy") ## 数组元素的批量追加 [root@PC1 test]# echo ${array1[*]} 100 800 aaa xxx yyy

。
006、数组元素的更新
[root@PC1 test]# declare -a array1 [root@PC1 test]# array1=(100 "xxx" "yyy" 800) [root@PC1 test]# echo ${array1[*]} 100 xxx yyy 800 [root@PC1 test]# array1[2]="kkkkk" ## 数组元素的更新 [root@PC1 test]# echo ${array1[*]} 100 xxx kkkkk 800

。
007、输出数组的索引值
a、
[root@PC1 test]# echo ${array1[*]}
100 xxx kkkkk 800
[root@PC1 test]# echo ${!array1[*]} ## 输出数组元素的索引值
0 1 2 3

。
b、
[root@PC1 test]# declare -a array1 [root@PC1 test]# array1[0]=100 [root@PC1 test]# array1[3]="aa" [root@PC1 test]# array1[6]="kkk" [root@PC1 test]# echo ${!array1[*]} 0 3 6

。
008、查看数组的长度
[root@PC1 test]# declare -a array1 [root@PC1 test]# array1[0]=100 [root@PC1 test]# array1[1]="aaa" [root@PC1 test]# array1[2]="kkk" [root@PC1 test]# echo ${array1[*]} 100 aaa kkk [root@PC1 test]# echo ${#array1[*]} ## 输出数组的长度 3

。
009、输出数组元素的长度
[root@PC1 test]# echo ${array1[*]}
100 aaa kkk
[root@PC1 test]# echo ${!array1[*]}
0 1 2
[root@PC1 test]# echo ${#array1[2]} ## 输出数组元素的长度
3

。

浙公网安备 33010602011771号