概述

在编程语言中,while循环(英语:while loop)是一种控制流程的陈述。利用一个返回结果为布林值(Boolean)的表达式作为循环条件,当这个表达式的返回值为“真”(true)时,则反复执行循环体内的程式码;若表达式的返回值为“假”(false),则不再执行循环体内的代码,继续执行循环体下面的代码。

下面用几个实例来理解下while怎么去用。

shell while循环语句(分享4个shell脚本实例)(1)


1、while创建定时任务

#!/bin/bash while true do uptime sleep 0.6 done

结果:

shell while循环语句(分享4个shell脚本实例)(2)


2、计算1-100的和

--bc命令实现

echo `seq -s 1 100`|bc

--while循环

#!/bin/bash i=1 ​ while [ "$i" -le 100 ] do ((b=b i)) ((i )) done echo $b

shell while循环语句(分享4个shell脚本实例)(3)


3、手机通讯计费功能

#!/bin/bash sum=1000 i=15 ​ ​ while [ $sum -ge 15 ] do cat<<EOF ================= 1.发短信 2.查余额 3.账户充值 4.退出 ================= EOF read -p "你要做什么呢?" Some case "$Some" in 1) sum=$((sum-i)) read -p "请输入发送短信的内容:" read -p "请输入收信人:" sleep 0.3 echo "发送成功." echo "您当前余额为$sum" ;; 2) echo "您当前余额为$sum" ;; 3) read -p "请输入你要充值的金额:" ChongZhi sum=$((sum ChongZhi)) echo "充值成功,当前余额为$sum" ;; 4) exit ;; *) echo "输入有误!" exit 2 esac done ​ echo "余额不足,请及时充值!"

shell while循环语句(分享4个shell脚本实例)(4)


4、获取取文件中的行,单词和字符

4.1 迭代获取文件中的每一行

--方法一 while read line; do echo $line; done < file.txt --方法二 cat file.txt|while read line do echo $line done --方法三 exec < file.txt while read line; do echo line; done

4.2 迭代获取每一个单词

for word in $line; do echo $word; done

4.3 迭代获取每一个字符

word=participate for ((i=0;i<${#word};i )) do echo ${word:1:1}; done

4.4 同时获取取文件中的行,单词和字符脚本

#!/bin/bash n=1 while read i do echo "第${n}行 $i" m=1 for x in $i do echo "第${m}个单词 $x" echo $x|grep -o . ((m )) done ((n )) done < $1

shell while循环语句(分享4个shell脚本实例)(5)

shell while循环语句(分享4个shell脚本实例)(6)


大家有空也可以自己测试一下,觉得有用的朋友多帮忙转发哦!后面会分享更多devops和DBA方面的内容,感兴趣的朋友可以关注下~

shell while循环语句(分享4个shell脚本实例)(7)

,