云计算:shell 编程-数组

 什么是数组?
 数组也是一种变量,常规变量只能保存一个值,数组可以保存多个值
 ​
 #普通数组:只能用整数作为数组的索引--默认值从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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值