数组:可以将一组数值放到其中,根据其下标来调用
随机数:用于随机取值,非常实用
- 搭配数组和随机数的实验,随机选择早上的早餐
#!/bin/bash
eat[1]="汉堡"
eat[2]="油条"
eat[3]="炸鸡"
eat[4]="包子"
eat[5]="泡面"
eat[6]="煎饼"
eat[7]="饺子"
eat[8]="嫂子"
eat[9]="牛奶"
eatnum=9 ====>总个数
check=$(($RANDOM * $eatnum / 32767 + 1 ))
echo "your may eat ${eat[${check}]}"
echo "your may eat ${eat[$check]}"
#####执行结果
[root@k8s-node2 ~]# ./what_to_eat.sh
your may eat 牛奶
your may eat 牛奶
- 随机选择三种不同早餐
#!/bin/bash
eat[1]="汉堡"
eat[2]="油条"
eat[3]="炸鸡"
eat[4]="包子"
eat[5]="泡面"
eat[6]="煎饼"
eat[7]="饺子"
eat[8]="嫂子"
eat[9]="牛奶"
eatnum=9
eated=0
while [ "$eated" -lt 3 ]; do
check=$(( $RANDOM * $eatnum / 32767 + 1 ))
mycheck=0
if [ $eated -ge 1 ];then
for i in `seq $eated`
do
if [ ${eatedcon[$i]} == $check ]; then
mycheck=1
fi
done
fi
if [ $mycheck == 0 ];then
echo "your may eat$ ${eat[$check]}"
eated=$(( $eated + 1 ))
eatedcon[$eated]=$check
fi
done
####执行结果
[root@k8s-node2 ~]# ./what_to_eat02.sh
your may eat$ 牛奶
your may eat$ 泡面
your may eat$ 饺子
学习笔记
网友评论