我理解的数组是把许多元素排列到一个集合里面,它也是变量的一种
数组定义的方法:
[root@server1 test]# array=(1 2 3 4) ##定义了一个数组
查看整个数组的方法:
[root@server1 test]# echo ${array[*]}
1 2 3 4
[root@server1 test]# echo ${array[@]}
1 2 3 4
##这两种方法都可以查看整个数组
查看某个数组元素的方法:
[root@server1 test]# echo ${array[0]}
1
[root@server1 test]# echo ${array[1]}
2
[root@server1 test]# echo ${array[3]}
4
##数组中的元素从0开始计数,比如例子中的1对应的是第0号元素,4对应的是第3号元素
查看某个区间内的数组元素:
查看1号元素到2号元素:
[root@server1 test]# echo ${array[@]:1:2}
2 3
##此命令表示,显示从一号元素开始向后的两个元素
替换某个元素:
[root@server1 test]# array[3]=old
[root@server1 test]# echo ${array[@]}
1 2 3 old
##将3号元素替换为了old,这中变化为永久变化
[root@server1 test]# echo ${array[@]/3/ha}
1 2 ha old
[root@server1 test]# echo ${array[@]}
1 2 3 old
##将3(2号元素)换成ha,但只是暂时的替换
删除数组:
[root@server1 test]# unset array[0]
[root@server1 test]# echo ${array[*]}
2 3 old
##删除0号元素,永久性的
[root@server1 test]# unset array
[root@server1 test]# echo ${array[*]}
##删除整个数组,永久性的
=============================
另外两种种定义数组的方法:
[root@server1 test]# array=([1]=one [2]=two [3]=three)
[root@server1 test]# echo ${array[*]}
one two three
[root@server1 test]# echo ${array[1]}
one
##此种方法定义,初始序号即为自己所设定的,不一定再为0
[root@server1 test]# array=($(ls))
[root@server1 test]# echo ${array[*]}
1-100.sh bendi.sh b.log break-1.sh cad case.sh chuancan.sh c.log cpmy.sh cuangai.sh func01.sh fuzai.sh hanshu.sh httpd.sh information_schema ip.sh mariadb.sh md5.sh my.sh mysql oldboy performance_schema ping.sh plus_color3.sh plus_color.sh read_panduan.sh shuzu.sh tables.sh test.sh tianjin.sh uptime.log user.sh web.sh while.sh yuancheng.sh zhixing.sh
##此种方法较为常用,将ls的输出结果定义为数组元素