linux运维基础day05数组:

一、数组的分类

1)普通数组,只能以数字整数作为索引(元素名称,下标)

2)关联数组,可以以字符串作为索引

语法结构:

数组名称 [元素名称]=元素的值

1、普通数组

数组定义方法:

 第一种:按照索引定义

[root@test ~]# array[0]=shell
[root@test ~]# array[1]=mysql
[root@test ~]# array[2]=docker

第二种:直接赋值

#直接赋值
[root@test ~]# array=(shell test hehe doker k8s)
[root@test ~]# echo ${array[*]}
shell test hehe doker k8s

#直接赋值和索引赋值结合
[root@test ~]# array=([5]=shell mysql reedis [20]=hehe)
[root@test ~]# echo ${array[*]}
shell mysql reedis hehe
[root@test ~]# echo ${!array[*]}
5 6 7 20

#支持命令
[root@test ~]# array=(`echo hehe mysql docker`)
[root@test ~]# echo ${array[*]}
hehe mysql docker
[root@test ~]# echo ${!array[*]}
0 1 2

unset array 取消数组

查看数组中的值

#查看数组中的值
[root@test ~]# echo ${array[0]}
shell
[root@test ~]# echo ${array[1]}
mysql
[root@test ~]# echo ${array[2]}
docker
[root@test ~]# echo ${array[*]}
shell mysql docker
[root@test ~]# echo ${array[@]}
shell mysql docker

#查看索引
[root@test ~]# echo ${!array[*]}
0 1 2

案例:两种遍历数组方式

#!/bin/bash
#定义数组
ip=(
10.0.0.1
10.0.0.2
10.0.0.3
10.0.0.4
10.0.0.5
)

#1、按照内容遍历
for i in ${ip[*]}
do
	ping -c1 -W1 $i &>/dev/null
	if [ $? -eq 0 ];then
	  echo $i 在线
	fi
done

#2、按照索引遍历
for i in ${!ip[*]}
do
	echo ${ip[$i]}
done

2、关联数组

定义方式

#普通定义方式无法定义关联数组
[root@test day05]# array[index1]=shell
[root@test day05]# array[index2]=mysql
[root@test day05]# array[index3]=redis
[root@test day05]# echo ${array[*]}
redis

[root@test day05]# declare -A array #需要先将数组声明为关联数组
[root@test day05]# array[index1]=shell
[root@test day05]# array[index2]=mysql
[root@test day05]# array[index3]=redis
[root@test day05]#  echo ${array[*]}
shell mysql redis

案例:统计字符出现的次数

#创建一个包含字符的文件
[root@test day05]# cat sex.txt 
f
f
m
m
f
f
m
m
x
#编写脚本读取文件中字符出现的次数
[root@test day05]# cat sex.sh 
#!/bin/bash
declare -A array
while read line
do
	let array[$line]++

done<sex.txt

for i in ${!array[*]}
do
	echo  $i 出现了 ${array[$i]} 次
done

[root@test day05]# sh sex.sh 
f 出现了 4 次
m 出现了 4 次
x 出现了 1 次 

抓阄案例:

[root@test day05]# cat zhuajiu.sh 
#需求:
#1.输入姓名,姓名后面出现一个1-100的随机数
#2.出现过的数字不能再出现
#3.取随机数的top3
#!/bin/bash
while true
do
	read -p "请输入你的姓名: " name
	if [ $name == ok ];then
	  echo "抓阄完毕排序如下 "
	  sort -rnk2 ran.txt
	  exit
	fi
	while true
	do
	  ran=`echo $((RANDOM%10+1))`
	  if [ `cat ran.txt|grep -w $ran|wc -l` -eq 1 ];then
	    continue
	  else 
	  echo -e "$name \t $ran"|tee -a ran.txt
	    break
	  fi
	done
done

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值