for语句的结构
使用for循环语句时,需要指定一个变量及可能的取值列表,针对每个不同的取值重复执行相同的命令序列,直到变量值用完退出循环。在这里,“取值列表”称为 for语句的执行条件,其中包括多个属性相同的对象,需要预先指定(如通讯录、IP黑名单)。
示例
根据列表给定的加班用户,给相应的用户工资加100元
分析:
- 确定用户名单
- 根据用户名单加100元
步骤 - 一:给定名单
- 二:位置变量给定用户和加班天数,算加班工资
[root@localhost ~]# vi jiaban.txt #添加测试用户
lisi
liwu
liliu
[root@localhost ~]#vi jiaban1.sh
#!/bin/bash
# 加班工资bash_money=5000
list=$(cat /root/jiaban.txt)
for user in $list
do
money=$(expr $bash_money + 100)
echo "$user salary is $money"
done
[root@localhost ~]# sh jiaban1.sh
lisi salary is 5100
liwu salary is 5100
liliu salary is 5100
[root@localhost ~]# vi jiaban2.sh #不是固定工资 ,变量
#!/bin/bash
# 加班工资
base_money=5000
for user in $1
do
money=$(expr $base_money + 100 \* $2)
echo "$user salary is $money"
done
[root@localhost ~]# chmod +x jiaban2.sh
[root@localhost ~]#./jiaban2.sh lisi 5
lisi salary is 5500
[root@localhost ~]# ./jiaban2.sh liwu 10
liwu salary is 6000
[root@localhost ~]# ./jiaban2.sh liliu 15
liliu salary is 6500
while语句的结构
for循环语句非常适用于列表对象无规律,且列表来源已固定(如某个列表文件)的场合。而对于要求控制循环次、操作对象按数字顺序编号、按特定条件执行重复操作等情况,则更适合使用另外一种循环——while语句
示例
由脚本预先生成一个随机的价格数目(0~999)作为实际价格,判断用户猜测的价格是否高出或低于实际价格,给出相应提示后再次要求用户猜测;一直到用户猜中实际价格为止,输出用户共猜测的次数、实际价格。
主要设计思路如下:通过环境变量RANDOM可获得一个小于2^16的随机整数,计算其与1000 的余数即可获得0~999的随机价格:反复猜测操作可以通过以 true作为测试条件的 while 循环实现,当用户猜中实际价格时终此循环:判断猜测价格与实际价格的过程采用if 语句实现,嵌套在while 循环体内;使用变量来记录猜测次数。
[root@localhost ~]# vim game.sh
#!/bin/bash
# 竞猜价格
price=$(expr $RANDOM % 1000)
times=0
echo "商品实际价格范围为0-999,猜猜看是多少?"
while ture #while(true)作为无线循环,经常在不知道循环次数的时候使用
do
read -p "请输入您竞猜的价格?"
int let times++
if [ $int -eq $price ]
then echo "恭喜您猜对了,实际价格是¥price" "您一共猜了$times次";break
elif [ $int -gt $price ]
then echo "太高了"
else
echo "太低了"
fi
done
[root@localhost ~]# chmod +x game.sh
[root@localhost ~]# ./game.sh
商品实际价格范围为0-999,猜猜看是多少?
请输入您竞猜的价格?
500太高了
请输入您竞猜的价格?
300太低了
请输入您竞猜的价格?350
恭喜您猜对了,实际价格是¥price echo 您一共猜了3次
until语句的结构
until循环与while 循环类似,while 循环能实现的脚本until同样也可以实现,但区别是while 循环在条件为真是继续执行循环,而until则是在条件为假时执行循环
示例
计算1-50的和算法:计算从1到50的和,从1开始相加,采用循环的方式,每次循环后加1,将得到的值加入计算的和中数字,运算采用的是 let 方式,直到加到50为止。方法1
[root@localhost ~]# vi sum_until.sh
#!/bin/bash
i=0
s=0
until [ $i -eq 50 ]
do
let i=$i+1
let s=$s+$i
done
echo '1-50的和为:' $s
[root@localhost ~]# chmod +x sum_until.sh
[root@localhost ~]# ./sum_until.sh
1-50的和为: 1275