shell脚本 ---- 数组应用

本文介绍了Shell数组变量,包括普通数组和关联数组。普通数组只能用整数作索引,关联数组可用字符串作索引。文中详细说明了两种数组的定义方法,有一次赋一个值和一次赋多个值两种方式,还介绍了查看数组和访问数组元素的操作。

Shell 数组变量

shell默认是普通数组  如果要定义关联数组 首先要先定义 declare -A  数组名
========================================================
普通数组:只能使用整数作为数组索引
关联数组:可以使用字符串作为数组索引
 

一、普通数组


定义数组:


方法一: 一次赋一个值
数组名[下标]=变量值
# array1[0]=pear
# array1[1]=apple
# array1[2]=orange
# array1[3]=peach


方法二: 一次赋多个值
# array2=(tom jack alice)
# array3=(`cat /etc/passwd`) 希望是将该文件中的每一个行作为一个元数赋
值给数组 array3
# array4=(`ls /var/ftp/Shell/for*`)
# array5=(tom jack alice "bash shell")
# colors=($red $blue $green $recolor)
# array5=(1 2 3 4 5 6 7 "linux shell" [20]=puppet)    第20位是puppet
查看数组:
# declare -a
declare -a array1='([0]="pear" [1]="apple" [2]="orange" [3]="peach")'
declare -a array2='([0]="tom" [1]="jack" [2]="alice")'
访问数组元数:
# echo ${array1[0]} 访问数组中的第一个元数
# echo ${array1[@]} 访问数组中所有元数 等同于 echo ${array1[*]}
# echo ${#array1[@]} 统计数组元数的个数
# echo ${!array2[@]} 获取数组元数的索引
# echo ${array1[@]:1} 从数组下标 1 开始
# echo ${array1[@]:1:2} 从数组下标 1 开始,访问两个元素

 


二、关联数组


定义关联数组:
申明关联数组变量
# declare -A ass_array1
# declare -A ass_array2
方法一: 一次赋一个值
数组名[索引]=变量值
# ass_array1[index1]=pear
# ass_array1[index2]=apple
# ass_array1[index3]=orange
# ass_array1[index4]=peach
方法二: 一次赋多个值
# ass_array2=([index1]=tom [index2]=jack [index3]=alice  [index4]='bash shell')
查看数组:
# declare -A
declare -A ass_array1='([index4]="peach" [index1]="pear" [index2]="apple" [index3]="orange" )'
declare -A ass_array2='([index4]="bash shell" [index1]="tom" [index2]="jack" [index3]="alice" )'
访问数组元数:
# echo ${ass_array2[index2]} 访问数组中的第二个元数
# echo ${ass_array2[@]} 访问数组中所有元数 等同于 echo ${array1[*]}
# echo ${#ass_array2[@]} 获得数组元数的个数
# echo ${!ass_array2[@]} 获得数组元数的索引

 

#!/bin/bash
while read line
do
        hosts[i++]=$line
done </etc/hosts

echo "hosts first: ${hosts[0]}"
for i in ${!hosts[@]}
do
        echo "$i: ${hosts[$i]}"
done
#!/bin/bash
OLD_IFS=$IFS
IFS=$'\n'
for line in `cat /etc/hosts`
do
        hosts[i++]=$line
done

for i in ${!hosts[@]}
do
        echo "$i : ${hosts[$i]}"
done

IFS=$OLD_IFS

统计男女人数

#!/bin/bash
declare -A sex
while read line
do
        type=`echo $line | awk '{print $2}'`
        let sex[$type]++
done < ./sex.txt

for i in ${!sex[@]}
do
        echo "$i :  ${sex[$i]}"
done
#!/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

 

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

卡搜偶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值