shell编程--数组
数组示例
#变量
name=meinanzi
echo ${name}
meinanzi
echo ${name:3:3}
nan
echo ${name:6:2}
zi
echo ${name:0:3}
mei
#数字分别是索引的起始位置和步长
echo ${name:3}
nanzi
#没有步长就全部显示出来
#数组
hero=(1111 2222 3333 4444)
hero=([0]=1111 [1]=2222 [2]=3333 [3]=4444)
#关联数组
declare -A position
position=([up]=1111 [down]=2222 [left]=3333)
数组定义
array2=(tom jack rose)
array3=(`cat /etc/passwd`)
array4=(`ls /var/ftp/Shell/for*`)
array5=(tom alice "bash shell")
red=111
blue=222
colors=($red $blue $green $recolor)
array6=(1 2 3 4 5 6 7 "linux shell" [20]=saltstack)
#逐一定义
array7[0]=pear
array7[1]=apple
array7[2]=orange
array7[3]=peach
#多用于循环中使用
数组查看
#描述所有数组
declare -a
declare -a | grep array7
#使用echo
echo ${array} #查看第一个元素
echo ${array[0]}
echo ${array[@]} #分散字符集
echo ${array[*]} #逐一字符集
echo ${#array[@]} #统计数组元素的个数
echo ${!array[@]} #获取数组元素的索引
echo ${array[@]:1} #从数组下标1开始
echo ${array[@]:1:2} #从数组下标1开始,显示2个元素
关联数组
使用前先声明,索引值可以自定义
declare -A ass1
ass1[index1]=pear
ass1[index2]=apple
ass1[index3]=name
ass1[index4]=peach
ass1[index5]=orange
###################
ass1=([index1]=pear [index2]=apple [index3]=name [index4]=peach [index5]=orange)
##################
echo ${ass1[*]}
echo ${!ass1[*]}
案例
案例1
while脚本快速定义数组
#/bin/bash
while read line
do
hosts[i++]=$line
done < /etc/hosts
for i in ${!host[@]}
do
echo "$i : ${hosts[$i]}"
done
案例2
for脚本快速定义数组
#!/bin/bash
for line in `cat /etc/hosts`
do
hosts[++i]=$line
done
for in in ${!hosts[@]}
do
echo "$i : ${hosts[$i]}"
done
for循环是空格分隔,while read line 是行分割
#!/bin/bash
OLD_IFS=$IFS #保存旧的分隔符
IFS=$'\n' #定义for的字段分割符
for line in `cat /etc/hosts`
do
hosts[++i]=$line
done
for in in ${!hosts[@]}
do
echo "$i : ${hosts[$i]}"
done
IFS=$OLD_IFS #还原分割符
案例3
数组统计性别
vim sex.txt
jack m
alice f
tom m
#!/bin/bash
declare -A sex
while read line
do
type=`echo $line | awk '{print $2}'`
#awk是流编辑器,详细了解看我专栏后面的文章
let sex[$type]++
done < /sex.txt
for i in ${!sex[@Z}
do
echo "$i : ${sex[$i]}"
done
案例4
数组统计,用户shell的类型和数量
#!/bin/bash
declare -A shells
while read ll
do
type=`echo $ll | awk -F: '{print $NF}'`
#-f用:作为分隔符,NF是最后一列
let shells[$type]++
done < /etc/passwd
for i in ${!shells[@]}
do
echo "$i : ${shells[$i]}"
done