变量只能存储一个值 数组可以存储多个值
数组的定义方式
1)普通数组 整数作为索引
root@bbb:/etc/nginx/conf.d# tt=(linux nginx php mysql)
root@bbb:/etc/nginx/conf.d# echo ${tt[*]}
linux nginx php mysql
root@bbb:/etc/nginx/conf.d# echo ${tt[0]}
linux
root@bbb:/etc/nginx/conf.d# echo ${!tt[*]}
0 1 2 3
root@bbb:~# echo ${#tt[@]}
5
root@bbb:~# array=(`cat /etc/passwd`)
root@bbb:~# declare -a
declare -a array='([0]="root:x:0:0:root:/root:/bin/bash" [1]="daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin" [2]="bin:x:2:2:bin:/bin:/usr/sbin/nologin" [3]="sys:x:3:3
2)关联数组 字符串作为索引 定以前必须先声明
root@bbb:~# unset info
root@bbb:~# declare -A info
root@bbb:~# info=([name]=yt [age]=33 [skill]=linux)
root@bbb:~# echo ${info[age]}
33
root@bbb:~# echo ${info[*]}
yt 33 linux
root@bbb:~# echo ${!info[*]}
name age skill
数组遍历与循环
root@bbb:~# cat test.sh
#!/bin/bash
i=0
while read line
do
array[i++]=${line}
done </etc/hosts
for i in `echo ${!array[*]}`
do
echo "${array[$i]}"
done
运用数组的索引 取出男女的个数
[root@RainGod ~]# cat sex.txt
jack m
clice f
tom m
rose f
robin m
yt m
#!/bin/bash
declare -A sex
while read line
do
#把性别当做索引
type=$(echo $line|awk '{print $2}')
#定义一个关联数组 相同的索引加1
let sex[$type]++
done<sex.txt
#echo ${sex[f]}
#打印sex数组的索引
for i in `echo ${!sex[*]}`
do
#取出对应索引对应的值
echo $i ${sex[$i]}
done