变量:存储单个元素的内存空间
数组:存储多个元素的连续的内存空间,相当于多个变量的集合
数组名和索引
索引的编号从0开始,属于数值索引
索引可支持使用自定义的格式,而不仅是数值格式,即为关联索引,版本之后开始支持
bash的数组支持稀疏格式(索引不连续)
7.2声明数组关联数组必须先声明,再使用declare-AARRAY_NAME
注意:两者不可相互转换
7.3数组赋值数组元素的赋值
(1)一次只赋值一个元素
ARRAY_NAME[INDEX]=VALUE
范例:
weekdays[0]="Sunday"weekdays[4]="Thursday"
(2)一次赋值全部元素
ARRAY_NAME=("VAL1""VAL2""VAL3")范例:
title=("ceo""coo""cto")num=({0..10})alpha=({a..g})file=(*.sh)(3)只赋值特定元素
ARRAY_NAME=([0]="VAL1"[3]="VAL2")
(4)交互式数组值对赋值
read-aARRAY
范例:
[root@centos8~]declare-acourse-bash:declare:course:cannotconvertassociativetoindexedarray[root@centos8~]declare-Afile-bash:declare:file:cannotconvertindexedtoassociativearray7.4显示所有数组
显示所有数组:
declare-a
范例:
[root@centos8~]如果省略[INDEX]表示引用下标为0的元素
范例:
[root@centos8~]echo${title[1]}coo[root@centos8~]echo${title[2]}cto[root@centos8~]echo${title[@]}ceocoocto[root@centos8~]ARRAY_NAME[*]}${echo${echo${title[*]}ceocoocto[root@centos8~]echo${title[*]}ceocto删除整个数组
unsetARRAY
范例:
[root@centos8~]echo${title[*]}[root@centos8~]要跳过的元素个数number取偏移量之后的所有元素{ARRAY[@]:offset}范例:
[root@centos8~]echo${num[*]:2:3}234[root@centos8~]ARRAY[*]}]=valueARRAY[${num[${echo${echo${num[@]}012345678910117.8关联数组declare-AARRAY_NAMEARRAY_NAME=([idx_name1]='val1'[idx_name2]='val2‘)
注意:关联数组必须先声明再调用
范例:
[root@centos8~]name[cto]=wang[root@centos8~]echo${name[ceo]}zhang[root@centos8~]echo${name[coo]}zhang[root@centos8~]declare-Aname-bash:declare:name:cannotconvertindexedtoassociativearray[root@centos8~]declare-Aname[root@centos8~]name[cto]=wang[root@centos8~]echo${name[coo]}zhang[root@centos8~]echo${name[cto]}wang[root@centos8~]!/bin/bashdeclare-iminmaxdeclare-anumsfor((i=0;i10;i++));donums[$i]=$RANDOM[$i-eq0]min=${nums[0]}max=${nums[0]}continue[${nums[$i]}-gt$max]max=${nums[$i]}[${nums[$i]}-lt$min]min=${nums[$i]}doneecho"Allnumbersare${nums[*]}"echoMaxis$maxechoMinis$min范例:编写脚本,定义一个数组,数组中的元素对应的值是/var/log目录下所有以.log结尾的文件;统计出其下标为偶数的文件中的行数之和
declare-afilesfiles=(/var/log/*.log)declare-ilines=0foriin$(seq0$[${#files[*]}-1]);doif[$[$i%2]-eq0];thenletlines+=$(wc-l${files[$i]}|cut-d''-f1)fidoneecho"Lines:$lines"练习1.输入若干个数值存入数组中,采用冒泡算法进行升序或降序排序
2.将下图所示,实现转置矩阵
123147
456===258
789369
3.打印杨辉三角形
【电子版领取见下图!!】