摘要
數(shù)組的特性就是一組數(shù)據(jù)類型相同的集合,雖然shell是弱類型,但是我們也可以將其數(shù)組分為
數(shù)據(jù)類型的數(shù)組和字符串類型的數(shù)組兩類
shell的數(shù)組元素之間用空格分隔開
數(shù)組操作
假設(shè)有以下兩個(gè)數(shù)組
array1=(1 2 3 4 5 6)
array2=("James" "Colin" "Harry")
- 數(shù)據(jù)變量名默認(rèn)輸出
默認(rèn)直接輸出變量的話,其輸出值默認(rèn)為第一個(gè)元素的值,下標(biāo)從0開始
root@pts/1 $ echo $array1
1
root@pts/1 $ echo $array2
James
- 獲取數(shù)組元素
格式:${數(shù)組名[下標(biāo)]},下標(biāo)從0開始,下標(biāo)為*或@代表整個(gè)數(shù)組內(nèi)容
root@pts/1 $ echo ${array1[2]}
3
root@pts/1 $ echo ${array2[1]}
Colin
## 獲取全部元素
root@pts/1 $ echo ${array2[*]}
James Colin Harry
root@pts/1 $ echo ${array2[@]}
James Colin Harry
- 獲取數(shù)組長度
格式:${#數(shù)組名[*或@]}
root@pts/1 $ echo ${#array1[@]}
6
root@pts/1 $ echo ${#array2[*]}
3
- 數(shù)組遍歷
root@pts/1 $ for item in ${array2[@]}
> do
> echo "The name is ${item}"
> done
The name is James
The name is Colin
The name is Harry
- 數(shù)組元素賦值
格式:數(shù)組名[下標(biāo)]=值,如果下標(biāo)不存在,則新增數(shù)組元素; 下標(biāo)已有,則覆蓋數(shù)組元素值
root@pts/1 $ array1[2]=18
root@pts/1 $ echo ${array1[*]}
1 2 18 4 5 6
root@pts/1 $ array2[4]="Betty"
root@pts/1 $ echo ${array2[*]}
James Colin Harry Betty
- 數(shù)組切片
格式:${數(shù)組名[*或@]:起始位:長度},截取部分?jǐn)?shù)組,返回字符串,中間用空格分隔;將結(jié)果使用(),則得到新的切片數(shù)組
root@pts/1 $ echo ${array2[*]}
James Colin Harry Betty
root@pts/1 $ echo ${array2[*]:1:3}
Colin Harry Betty
root@pts/1 $ array3=(${array2[*]:1:2})
ks-devops [~] 2018-01-25 20:30:16
root@pts/1 $ echo ${array3[@]}
Colin Harry
- 數(shù)組元素替換
格式:${數(shù)組名[*或@]/查找字符/替換字符}, 不會(huì)修改原數(shù)組;如需修改的數(shù)組,將結(jié)果使用“()”賦給新數(shù)組
root@pts/1 $ echo ${array2[*]}
James Colin Harry Betty
root@pts/1 $ echo ${array2[*]/Colin/Colin.Liu}
James Colin.Liu Harry Betty
root@pts/1 $ array4=(${array2[*]/Colin/Colin.liu})
root@pts/1 $ echo ${array4[*]}
James Colin.liu Harry Betty
- 刪除元素
格式:
unset 數(shù)組,清除整個(gè)數(shù)組;
unset 數(shù)組[下標(biāo)],清除單個(gè)元素
root@pts/1 $ echo ${array2[*]}
James Colin Harry Betty
root@pts/1 $ echo ${array4[*]}
James Colin.liu Harry Betty
root@pts/1 $ unset array4
root@pts/1 $ unset ${array2[3]}
root@pts/1 $ echo ${array2[*]}
James Colin Harry Betty
root@pts/1 $ echo ${array4[*]}
root@pts/1 $