什么是数组?
数组也是一种变量,常规变量只能保存一个值,数组可以保存多个值
#普通数组:只能用整数作为数组的索引--默认值从0开始 下标
#关联数组:可以使用字符串作为数组的索引
数组定义
普通数组定义:
[root@linux-server script]# books=( linux shell awk sed ) ---在python中叫列表
引用:${array_name[index]} #引用
[root@linux-server script]# echo ${books[0]}
linux
[root@linux-server script]# echo ${books[1]}
shell
[root@linux-server script]# echo ${books[2]}
awk
#关联数组需要提前声明
Declare命令:
[test @test test]# declare [-选项]
参数说明:
-a :#定义为数组--array
-A : #定义关联数组
例1
declare -A myarry1
[root@linux-server script]# declare -A myarry1
[root@linux-server script]# myarry1=([name]=soso666 [sex]=man [age]=18)
[root@linux-server script]# echo ${myarry1[name]}
soso666
[root@linux-server script]# echo ${myarry1[age]}
18
定义方法1:
[root@linux-server script]# declare -a myarry=(5 6 7 8)
[root@linux-server script]# echo ${myarry[2]}
显示结果为 7
定义方法3:
#语法:数组名[index]=变量值
#!/bin/bash
area[11]=23
area[13]=37
area[51]="UFO"
示例
[root@linux-server script]# vim shuzu.sh
#!/bin/bash
NAME[0]="BJ"
NAME[1]="SH"
NAME[2]="SZ"
NAME[3]="GZ"
NAME[4]="HZ"
NAME[5]="ZZ"
echo "First Index: ${NAME[0]}"
echo "Second Index: ${NAME[1]}"
echo "sixth Index: ${NAME[5]}"
输出结果
[root@linux-server script]# bash shuzu.sh
First Index: BJ
Second Index: SH
sixth Index: ZZ
访问数组
当设置任何数组变量时,可以访问它
[root@linux-server script]# aa=(haha heihei baibai)
[root@linux-server script]# echo ${aa[0]} #访问数组中的第一个元素
[root@linux-server script]# echo ${aa[@]} #访问数组中所有的元素 等同与echo ${aa[*]}
[root@linux-server script]# echo ${#aa[@]} #统计元素的个数
[root@linux-server script]# echo ${!aa[@]} #打印索引
您可以访问数组中的所有项目通过以下方式之一:
${array_name[*]}
${array_name[@]}
数组遍历案例
[root@newrain array]# cat array01.sh
#!/bin/bash
while read line
do
host[i++]=$line
done </etc/hosts
echo
for i in ${!host[@]}
do
echo "$i:${host[$i]}"
done
遍历数组for
[root@newrain array]# cat array02.sh
#!/bin/bash
#IFS=$'\n'
for line in `cat /etc/hosts`
do
host[j++]=$line
done
for i in ${!host[@]}
do
echo ${host[$i]}
done
#注意:for循环中会将tab\空格\回车作为分隔符默认为空格.
[root@localhost ~]# vim count_shells.sh
#!/usr/bin/bash
declare -A shells
while read line
do
type=`echo $line | awk -F":" '{print $NF}'`
let shells[$type]++
done < /etc/passwd
for i in ${!shells[@]}
do
echo "$i: ${shells[$i]}"
done