数组:存储多个元素的连续的内存空间,相当于多个变量的集合
想要引用数组中的元素,需要数组名和索引号,索引号编号从0开始,属于数值索引。根据索引号的是否连续分为普通数组和关联属组
普通数组:索引号连续 (使用前可不声明)
关联属组:索引号可以不连续 ,也可是使用非整型的下表来索引属组中的元素。(使用前必须先声明)
声明属组:
declare -a ARRAY_NAME 普通数组 declare -A ARRAY_NAME: 关联数组
数组元素的赋值:
(1) 一次只赋值一个元素; ARRAY_NAME[INDEX]=VALUE
[root@localhost http2]# array[0]="red"
[root@localhost http2]# array[1]="blue"
[root@localhost http2]# array[2]="green"
[root@localhost http2]# array[3]="yellow"
(2) 一次赋值全部元素:
[root@localhost http2]# arr=("one" "two" "three")
(3) 只赋值特定元素: ARRAY_NAME=([0]="VAL1" [3]="VAL2" ...)
[root@localhost http2]# arrc=([0]="shui" [4]="qi")
(4) 交互式数组值对赋值 read -a ARRAY
[root@localhost http2]# read -a ARR
ni hao hello
引用数组
1、引用数组元素:${ARRAY_NAME[INDEX]}
[root@localhost http2]# echo ${array[0]}
red
[root@localhost http2]# echo ${array[1]}
blue
[root@localhost http2]# echo ${array[2]}
green
[root@localhost http2]# echo ${array[*]}
red blue green yellow
[root@localhost http2]#
[root@localhost http2]# echo ${!array[*]} //显示数组array的索引
0 1 2 3
2、数组的长度(数组中元素的个数)
${#ARRAY_NAME[*]} ${#ARRAY_NAME[@]}
[root@localhost http2]# echo ${#array[*]}
4
[root@localhost http2]# echo ${#array[@]}
4
[root@localhost http2]#
数组数据处理
1、引用数组中的元素:
所有元素:${ARRAY[@]}, ${ARRAY[*]}
[root@localhost http2]# echo ${array[@]}
red blue green yellow
[root@localhost http2]# echo ${array[*]}
red blue green yellow
数组切片:${ARRAY[@]:offset:number} offset: 要跳过的元素个数 number: 要取出的元素个数
[root@localhost http2]# echo ${array[@]}
red blue green yellow
[root@localhost http2]# echo ${array[@]:2:1} //2表示跳过前两个元素,1表示取出一个元素
green
取偏移量之后的所有元素${ARRAY[@]:offset}
[root@localhost http2]# echo ${array[@]}
red blue green yellow
[root@localhost http2]# echo ${array[@]:2} //表示跳过array属组中前两个元素,跳过前两个取出后面所有
green yellow
2、向数组中追加元素
ARRAY=("${ARRAY[@]}" "NEW")
[root@localhost http2]# echo ${array[*]} //添加元素之前
red green yellow bule
[root@localhost http2]# array=("${array[@]}" "white") //添加white元素
[root@localhost http2]# echo ${array[*]}
red green yellow bule white //成功添加
[root@localhost http2]#
3、删除数组中的某元素:导致稀疏格式
[root@localhost http2]# echo ${array[*]} //算出元素之前
red green yellow bule white
[root@localhost http2]# unset array[2] //删除索引号为2的元素
[root@localhost http2]# echo ${array[*]} //查看数组发现已经少了一个元素
red green bule white
[root@localhost http2]# echo ${!array[*]} //查看数组索引,2已经被删除!
0 1 3 4
关联数组:索引号可以不连续 ,也可是使用非整型的下表来索引属组中的元素。(使用前必须先声明)
declare -A ARRAY_NAME ARRAY_NAME=([idx_name1]=('val1' [idx_name2]='val2‘...)
[root@localhost http2]# declare -A A=([a]="abondan" [b]="banlance" [c]="curl")
[root@localhost http2]# echo ${A[*]} //查看关联数组A中的所有元素
abondan banlance curl
[root@localhost http2]# echo ${!A[*]} //查看关联属组的键值
a b c
[root@localhost http2]# echo ${#A[*]} //查看元素的个数
3
遍历一个关联数组可以用下面的方法:
[root@localhost http2]# declare -A A=([a]="abondan" [b]="banlance" [c]="curl")
[root@localhost http2]# for i in `echo ${!A[*]}`;do echo $i : ${A[$i]};done
a : abondan
b : banlance
c : curl
字符串处理
1、字符串切片
1)${#var}:返回字符串变量var的长度