一、數組介紹
一個變量只能存一個值,現實中很多值需要存儲,可以定義數組來存儲一類的值。
二、基本數組
1、概念:
數組可以讓用戶一次性賦予多個值,需要讀取數據時只需通過索引調用就可以方便讀出。
2、數組語法
數組名稱=(元素1 元素2 元素3)
[root@localhost test20210725]# list1=(1 2 3 4 5) [root@localhost test20210725]# list2=('a' 'b' 'c' 'd')
3、數組讀出
${數組名稱[索引]}
索引默認是元素在數組中的排隊編號,默認第一個從0開始
[root@localhost test20210725]# list1=(1 2 3 4 5) [root@localhost test20210725]# list2=('a' 'b' 'c' 'd') [root@localhost test20210725]# echo ${list1[0]} 1 [root@localhost test20210725]# echo ${list2[2]} c
4、數組賦值
[root@localhost test20210725]# list1=(1 2 3 4 5) [root@localhost test20210725]# list1[0]='1a' [root@localhost test20210725]# echo ${list1[0]} 1a
5、查看聲明過的數組
[root@localhost test20210725]# declare -a declare -a BASH_ARGC='()' declare -a BASH_ARGV='()' declare -a BASH_LINENO='()' declare -a BASH_SOURCE='()' declare -ar BASH_VERSINFO='([0]="4" [1]="2" [2]="46" [3]="2" [4]="release" [5]="x86_64-redhat-linux-gnu")' declare -a DIRSTACK='()' declare -a FUNCNAME='()' declare -a GROUPS='()' declare -a PIPESTATUS='([0]="127")' declare -a list1='([0]="1a" [1]="2" [2]="3" [3]="4" [4]="5")' declare -a list2='([0]="a" [1]="b" [2]="c" [3]="d")'
6、訪問數組元素
[root@localhost test20210725]# list1=(1 2 3 4 5 6 7 8 9 0) [root@localhost test20210725]# echo ${list1[0]} #訪問數組中第一個元素 1 [root@localhost test20210725]# echo ${list1[@]} #訪問數組中所有元素,@等同於*
1 2 3 4 5 6 7 8 9 0 [root@localhost test20210725]# echo ${list1[*]} 1 2 3 4 5 6 7 8 9 0 [root@localhost test20210725]# echo ${#list1[@]} #統計數組中元素個數 10 [root@localhost test20210725]# echo ${!list1[@]} #統計數組元素的索引 0 1 2 3 4 5 6 7 8 9 [root@localhost test20210725]# echo ${list1[@]:1} #從數組下標1開始 2 3 4 5 6 7 8 9 0 [root@localhost test20210725]# echo ${list1[@]:1:3} #從數組下標1開始,訪問3個元素 2 3 4
7、遍歷數組
(1)默認數組通過數組元素的個數進行遍歷
vim list_for.sh
#!/bin/bash list="rootfs usr data data2" for i in $list; do echo $i is appoint ; done
查看運行結果:
[root@localhost test20210725]# sh list_for.sh rootfs is appoint usr is appoint data is appoint data2 is appoint
三、關聯數組
1、概念:
關聯數組可以允許用戶自定義數組的索引,這樣使用起來更加方便、高效
2、定義關聯數組:
[root@localhost test20210725]# declare -A acc_array1 #聲明一個關聯數組
3、關聯數組賦值:
[root@localhost test20210725]# declare -A acc_array1 #聲明一個關聯數組 [root@localhost test20210725]# acc_array1=([name]='mrwhite' [age]=18) #賦值
4、關聯數組查詢:
[root@localhost test20210725]# declare -A acc_array1 #聲明一個關聯數組 [root@localhost test20210725]# acc_array1=([name]='mrwhite' [age]=18) #賦值 [root@localhost test20210725]# echo ${acc_array1[name]} mrwhite
5、關聯數組的遍歷:
[root@localhost test20210725]# vim ass_list_for.sh #!/usr/bin/bash ################################# # Author: Mr.white # # Create_Date: 2021-07-03 19:09:56 # # Version: 1.0 # ################################# declare -A acc_list acc_list=([name]='mrwhite' [age]=18) echo "數組acc_list的key value為:"
for key in ${!acc_list[@]} do #根據key取值 echo "$key <-> ${acc_list[${key}]}" done
查詢運行結果:
[root@localhost test20210725]# sh ass_list_for.sh 數組acc_list的key value為: name <-> mrwhite age <-> 18