linux 中 数组的常见操作

 

001、创建数组

[root@PC1 test02]# ay=(1 2 3 4)         ## 生成数组
[root@PC1 test02]# echo ${ay[*]}        ## 输出数组
1 2 3 4
[root@PC1 test02]# echo ${#ay[*]}       ## 输出数组的长度
4

 

002、

[root@PC1 test02]# ay=("a", "b", "c", "x")    ## 字符串数组
[root@PC1 test02]# echo ${ay[*]}             
a, b, c, x
[root@PC1 test02]# echo ${ay[@]}              ## 输出数组
a, b, c, x
[root@PC1 test02]# echo ${#ay[*]}             ## 输出数组的长度
4

 

003、输出单个数组元素的值

[root@PC1 test02]# ay=("a", "b", "c", "x")         ## 生成数组
[root@PC1 test02]# echo ${ay[0]}                   ## 输出单个元素的值
a,
[root@PC1 test02]# echo ${ay[2]}
c,
[root@PC1 test02]# for i in {0..3}; do echo ${ay[$i]}; done      ## 遍历
a,
b,
c,
x

 。

 

004、给数组的元素赋值

[root@PC1 test02]# ay=("x" "b" "k" "j")        ## 生成数组
[root@PC1 test02]# echo ${ay[*]}               ## 输出数组
x b k j
[root@PC1 test02]# ay[4]="m"                   ## 给数组的单个元素赋值
[root@PC1 test02]# echo ${ay[*]}               ## 输出数组
x b k j m

 

005、普通数组和关联数组

[root@PC1 test02]# declare array01                   ## 定义普通数组
[root@PC1 test02]# declare -A array02                ## 定义关联数组
[root@PC1 test02]# array01["a"]=1000
[root@PC1 test02]# array01["b"]=2000
[root@PC1 test02]# array02["a"]=1000
[root@PC1 test02]# array02["b"]=2000
[root@PC1 test02]# echo ${array01[*]}               ## 普通数组
2000
[root@PC1 test02]# echo ${array02[*]}               ## 关联数组
1000 2000
[root@PC1 test02]# echo ${array01["a"]}
2000
[root@PC1 test02]# echo ${array02["a"]}            ## 关联数组可以使用其他字符正确索引
1000

 

 

posted @ 2023-07-05 18:11  小鲨鱼2018  阅读(259)  评论(0)    收藏  举报