有2種數組: 索引數組 關聯數組(java里的Hashmap),用key關聯value 聲明數組: 引用數組:${ary[idx]} 必須加大括弧 直接訪問數組名,就是訪問第一個元素 給數組賦值 單個賦值:ary[idx]=val 多個賦值:ary=(val1 val2...) 跳躍賦值:ary=( ...
有2種數組:
- 索引數組
- 關聯數組(java里的Hashmap),用key關聯value
聲明數組:
#聲明索引數組
declare -a ary
#聲明關聯數組
declare -a ary
引用數組:${ary[idx]}
必須加大括弧
直接訪問數組名,就是訪問第一個元素
[root@localhost ~]# ani[0]=dog
[root@localhost ~]# ani[1]=cat
[root@localhost ~]# echo ani
ani
[root@localhost ~]# echo ani[0]
ani[0]
[root@localhost ~]# echo $ani[0]
dog[0]
[root@localhost ~]# echo ${ani[0]}
dog
[root@localhost ~]# echo ${ani[1]}
cat
給數組賦值
單個賦值:ary[idx]=val
多個賦值:ary=(val1 val2...)
[root@localhost ~]# ary=(1 2 3 4 ) [root@localhost ~]# echo $ary 1 [root@localhost ~]# echo ${ary[0]} 1 [root@localhost ~]# echo ${ary[2]} 3 [root@localhost ~]# echo ${ary[1]} 2 [root@localhost ~]# echo ${ary[3]} 4 [root@localhost ~]# echo ${ary[4]} [root@localhost ~]#
跳躍賦值:ary=([0]="aa" [3]="dd")
[root@localhost ~]# ary=([0]="aa" [3]="dd") [root@localhost ~]# echo ${ary[0]} aa [root@localhost ~]# echo ${ary[1]} [root@localhost ~]# echo ${ary[3]} dd
read讀取數組
就選項-a就是讀取數組
# read -a li
a b 1 d a2
[root@localhost ~]# echo $li
a
[root@localhost ~]# echo ${li[0]}
a
[root@localhost ~]# echo ${li[2]}
1
[root@localhost ~]# echo ${li[4]}
a2
取得數組元素的個數
- ${#ary[*]}
- ${#ary[@]}
取得數組中某個元素的長度
${#ary[indx/名字]}
得到數組的所以元素
- ${ary[*]}
- ${ary[@]}
關聯數組
關聯數組使用前最好先聲明,使用-A選項聲明。
[root@localhost scripts]# declare -A map
[root@localhost scripts]# map=([aa]=df12 [dd]=132432 [2]=12d)
[root@localhost scripts]# echo ${map[*]}
132432 df12 12d
[root@localhost scripts]# echo ${map[aa]}
df12
[root@localhost scripts]# echo ${map[2]}
12d
[root@localhost ~]# declare -A l3
[root@localhost ~]# l3[a]=aa
[root@localhost ~]# l3[b]=bb
[root@localhost ~]# echo ${l3[a]}
aa
[root@localhost ~]# echo ${l3[b]}
bb
[root@localhost ~]# echo ${#l3[*]}
2
[root@localhost ~]# echo ${#l3[@]}
2
[root@localhost ~]# echo ${#l3[a]}
2
[root@localhost ~]# echo ${#l3[b]}
2
[root@localhost ~]# l3[c]=1dsfs
[root@localhost ~]# echo ${#l3[c]}
5
[root@localhost ~]# echo ${l3[*]}
aa bb 1dsfs
[root@localhost ~]# echo ${l3[@]}
aa bb 1dsfs
數組的切片
${ary[@]:offset:length}
- offset:從第幾個開始切
- length:切多長
[root@localhost scripts]# l1=(1 2 3 4 5 6)
[root@localhost scripts]# echo ${l1[@]:2:2}
3 4
刪除數組裡某個元素
# l1=(1 2 3 4 5 6)
[root@localhost scripts]# echo ${l1[@]:2:2}
3 4
[root@localhost scripts]# unset l1[1]
[root@localhost scripts]# echo ${l1[@]}
1 3 4 5 6
練習
1,生成10個隨機整數,求最大值
$RANDOM是內置變數,能生成隨機整數。
#!/bin/bash
#
declare -a rand
declare -i max=0
for i in {0..9}; do
rand[$i]=$RANDOM
echo ${rand[$i]}
if [ $max -lt ${rand[$i]} ]; then
max=${rand[$i]}
fi
done
echo "max is $max"
2,統計/var/log/*.log文件的行數之和。
關鍵點:files=(/var/log/*.log)。括弧里是globbing風格,會自動展開。
#!/bin/bash
#
declare -a files
declare -i lines
files=(/var/log/*.log)
for ((i=0;i<${#files[*]};i++)); do
let lines+=`wc -l ${files[$i]} | cut -d" " -f1`
done
echo $lines