> 文档中心 > shell脚本之循环语句 (for、while、until)

shell脚本之循环语句 (for、while、until)

文章目录

  • 一、for 循环语句
  • 二、while 循环语句
  • 三、until 循环语句
  • 四、循环控制语句
  • 五、总结

一、for 循环语句

1.语法结构:
(1)列表循环
(2)不带列表循环
(3)类C风格的for循环

格式:for  变量名  in  取值列表do命令序列done

2.用法:

读取不同的变量值,用来逐个执行同一组命令

for循环经常使用在已经知道要进行多少次循环的场景
shell脚本之循环语句 (for、while、until)
例1:显示从0到9的数字

方法一:#!/bin/bash for i in {0..9}do echo $idone方法二:#!/bin/bash for i in $(seq 0 9)do echo $idone

shell脚本之循环语句 (for、while、until)

shell脚本之循环语句 (for、while、until)
shell脚本之循环语句 (for、while、until)
shell脚本之循环语句 (for、while、until)

例2:打印五次hello world

#!/bin/bashfor i in {1..5}doecho hello worlddone

shell脚本之循环语句 (for、while、until)
shell脚本之循环语句 (for、while、until)

例3:1到10 之间奇数和

#/bin/bashsum=0for i in {1..10..2}do  sum=$[sum+i]  let i++doneecho "10以内的奇数和为:$sum"

shell脚本之循环语句 (for、while、until)
shell脚本之循环语句 (for、while、until)

例4:输出0-50之间的偶数

[root@server ~]# vim for.sh#!/bin/bashfor i in {0..50..2]   ###..2代表步长为2,每隔2个doecho $idone

shell脚本之循环语句 (for、while、until)
shell脚本之循环语句 (for、while、until)

附小技巧:花括号{}和seq在for循环的应用

for i in {1..50..2]   1-50的奇数for i in {2..50..2)   1-50的偶数for i in {10..1}    1-10倒序排列for i in $(seq 10)    1-10正序排列for i in $(seq 10 -1 1)   1-10倒序排列for i in $(seq 1 2 10)    1-10的奇数,中间为步长for i in s (seq 0 2 10)   1-10的偶数,中间为步长

不带列表循环执行时由用户指定参数和参数的个数决定的

格式:for 变量名docommanddone

例:打印hello world

[ root@server ~]# vim k.sh#!/bin/ bashfor idoecho hello worlddone[root&server ~]# sh k.sh     ###没有给脚本传参所以执行了没有结果[ root@server ~-]# sh k.sh a     ###把a赋值给变量i,i有值了它就开始执行do ..done了hello world

第二种:

for i doecho $idone[root@localhost ~]# sh k.sh helloworldhelloworld

类c风格的for循环

for ( (expr1;expr2;expr3))docommanddoneexpr1:定义变量并赋初值expr2:决定是否循环expr3:决定循环变量如何改变,决定循环什么时候退出

例:打印 1-5 迭代

#!/bin/bashfor  ((i=1;i<=5;i++) )doecho $idone注: i++ :  i=1+1  先赋值再运算  i=1  之后再 +1++i :  1+1=i  先运算再赋值  1+1  之后再 =i

shell脚本之循环语句 (for、while、until)

shell脚本之循环语句 (for、while、until)

例2:打印1-10的奇数

#! /bin/bashfor ( (i=1 ;i<=10;i+=2))     ###i=i+2doecho $idone

shell脚本之循环语句 (for、while、until)
shell脚本之循环语句 (for、while、until)

附:类c风格运算符用法

++   自身变量+1–    自身变量-1+=5  自身变量+5-=5  自身变量-5=5   自身变量5/=5  自身变量/5%=5  自身变量%5

例3:计算1-100的奇数和

#!/bin/bashsum=0for ( (i=1 ;i<=100 ;i+=2) )dolet sum=$i+$sumdoneecho "1-100的奇数和为:$sum"

shell脚本之循环语句 (for、while、until)
shell脚本之循环语句 (for、while、until)

其他案例:

例1:批量添加用户两种方式
1)以后缀批量变化添加

for i in {1..5}douseradd stu$iecho "123" | passwd --stdin stu$idone

shell脚本之循环语句 (for、while、until)
shell脚本之循环语句 (for、while、until)

2)脚本批量添加用户

#!/bin/bashULIST=$ (cat /root/users.txt)for UNAME in $ULISTdouseradd  $UNAMEecho "123456" | passwd --stdin $UNAME &>/dev/nulldone

shell脚本之循环语句 (for、while、until)

批量删除用户的脚本

#!/bin/bashULIST=$(cat /root/users.txt)for UNAME in $ULISTdouserdel -r $UNAME &>/ dev/ nulldone

shell脚本之循环语句 (for、while、until)

例2、根据IP地址列表检查主机状态
-c发送包的数量
-i发送ping包间隔
-W超时时间

1)根据文本查看

#!/bin/bashHLIST=$ (cat /root/ipadds.txt)for IP in $HLISTdoping -c 3 -i 0.2 -W 3 $IP &> /dev/nullif [ $? -eq 0 ];thenecho "Host $IP is up."elseecho "Host $IP is down . "fidone

shell脚本之循环语句 (for、while、until)

2)根据段查看

#!/bin/bashnetwork="192.168.10"for addr in { 1..254 }doping -c 2 -i 0.5 -w 3 $network.$addr &> /dev/nullif [ $? -eq 0 ] ;thenecho " $network. $addr is up"elseecho "$network.$addr is down"fidone

shell脚本之循环语句 (for、while、until)
shell脚本之循环语句 (for、while、until)

用户输入密码,脚本判断密码是否正确,输入正确提示正确信息,连续输错3次则报警

#!/bin/bashinit=123456for i in {1. .3}doread -p "请输入密码:" passif  [ $pass == $init ] ; thenecho “密码正确"exitfidoneecho“警告:密码错误"

shell脚本之循环语句 (for、while、until)

shell脚本之循环语句 (for、while、until)

二、while 循环语句

while循环一般用于有条件判断的循环,若判断条件为真,则进入循环,当条件为假就跳出循环

用法:

重复测试某个条件,只要条件成立则反复执行

常在不知道范围的时候成立

格式:while 条件测试操作do命令序列done

shell脚本之循环语句 (for、while、until)
例1:打印1-5

#!/bin/bashi=1while [ $i -le 5 ]do    echo $i    let i++   ###注意这里如果不改变$i的值,会变成死循环#i=$[$i+1]  //两种写法doneecho "最后i的值为: $i"

shell脚本之循环语句 (for、while、until)

shell脚本之循环语句 (for、while、until)

例2:输出1-100之间不能被3整除的数字

#!/bin/bashi=1while [ $i -le 100 ] do if [[ $i%3 -ne 0 ]] then echo "$i" fi let i++done

shell脚本之循环语句 (for、while、until)

shell脚本之循环语句 (for、while、until)

例3:打印1-100的和

#!/bin/bashi=1sum=0while [ $i -le 100 ]do let sum=$i+$sum let i++doneecho $sum

shell脚本之循环语句 (for、while、until)
shell脚本之循环语句 (for、while、until)

while死循环

while [ 1 -eq 1 ]  //写一个永远为真的表达式,1等于1这个条件永远为真,所以这个脚本会一直循环下去do    commanddone
while truedo    commanddone
while :do    commanddone

例:猜数字小游戏

#!/bin/bash pc_num=$[RANDOM%3+1]count=0while truedo    read -p "请输入一个数字:" user_num   if [ $user_num -eq $pc_num ]   thenecho "答对啦"      break   elif [ $user_num -gt $pc_num ]   then      echo "你的数字太大了"   else      echo "你的数字太小了"   fi   let count++done   echo 你输入的次数为:$count

shell脚本之循环语句 (for、while、until)
shell脚本之循环语句 (for、while、until)

例2:猜商品价格游戏
$random用于生成0—32767的随机数

第一种方法

#!/bin/bashPRICE=$(expr $RANDOM % 1000)a=0echo "商品实际价格范围为 0-999,猜猜看是多少?" while truedoread -p "请输入你猜测的价格数目:" n let a++if [ $n -eq $PRICE ] ; thenecho "恭喜你答对了,实际价格是 $PRICE" echo "你总共猜测了 $a 次"exit 0elif [ $n -gt $PRICE ] ; then echo "你猜高了!"elseecho "你猜低了!"fi done

shell脚本之循环语句 (for、while、until)
shell脚本之循环语句 (for、while、until)

第二种方法

#!/bin/bashsorce=$[$RANDOM % 1000]a=1num=0while[ $a -lt 2 ]doread -p "请输入你猜的价格(1-999之 间) :"  priceif [ $price -eq $sorce ] ; thenecho "恭喜你猜对了!"let num++let a++elif [ $price -gt $sorce ] ; thenecho "你猜高了!"let num++elif[ $price -lt $sorce ] ; thenecho "你猜小了!"let num++fidoneecho "你一共猜了$num次!"

shell脚本之循环语句 (for、while、until)

例3:实时监控本机内存和硬盘剩余空间,剩余内存小于500M、根分区剩余空间小于1000M 时,发送报警邮件给 root 管理员

#!/bin/bash#提取根分区剩余空间disk_size=$(df / |awk '/\//{print $4}')#提取内存剩余空间mem_size=$(free |awk '/Mem/{print $4}') while :do#注意内存和磁盘提取的空间大小都是以Kb 为单位if [ $disk_size ‐le 512000 -a $mem_size ‐le 1024000 ];then mail ‐s Warning root <<EOFInsufficient resources,资源不足EOFfi done

shell脚本之循环语句 (for、while、until)

三、until 循环语句

跟while相反,条件为假进入循环,条件为真退出循环

用法: 重复测试某个条件,只要条件不成立则反复执行

格式:until 条件测试操作do 命令序列done

shell脚本之循环语句 (for、while、until)
例1:计算1到100的和

#!/bin/bashsum=0i=0until [ $i -gt 100 ]do sum=$[sum+i] let i++doneecho "{1..100}的和:$sum"

shell脚本之循环语句 (for、while、until)
shell脚本之循环语句 (for、while、until)

死循环结构

until falsedo    commanddoneuntil [ 1 -ne 1 ]do    commanddone

案例:登录 zhangsan 用户 使用 root 发消息给zhangsan

#!/bin/bashusername=$1#判断信息格式if [ $# -lt 1 ];then  echo "Usage:`basename $0`  []"   exit 1fi#判断用户是否存在if grep "^$username:" /etc/passwd >/dev/null ;then : else   echo "用户不存在"   exit 1fi#用户是否在线,如果不在线每5秒联系一次until who|grep "$username" >/dev/nulldoecho "用户不存在" sleep 5donemes=$* echo $mes | write $username注:测试时切换下用户

shell脚本之循环语句 (for、while、until)

四、循环控制语句

for循环一般会搭配条件判断语句和流程控制语句一起执行,那么就会出现需要跳过循环和中止循环的情况,控制循环的命令有以下3个

1、continue
继续,但不会执行循环体内下面的代码了,开始重新开始下一次循环

例:打印1-5的数字,3不打印

#!/bin/bashfor ((i=1;i<=5;i++))do if [ $i -eq 3 ];then continue else echo $i fidone

shell脚本之循环语句 (for、while、until)
shell脚本之循环语句 (for、while、until)

结果是1245,3不输出,因为跳出后面的echo语句执行下一次循环了

2、break
打断,马上停止本次循环,执行循环体外的代码

例:1-10的数字,7后面的都不打印

#!/bin/bashfor ((i=1;i<=10;i++))do if [ $i -eq 8 ];then break else echo $i fidone

shell脚本之循环语句 (for、while、until)
shell脚本之循环语句 (for、while、until)

3、exit
直接跳出程序,后面可跟状态返回码如 exit 1等等

for i in {1..5}doif [ $i -eq 3 ];then exit  100 else echo $ifidoneecho $i

shell脚本之循环语句 (for、while、until)
shell脚本之循环语句 (for、while、until)

直接跳出程序所以不会执行最后的echo hi,并且返回码是100通过$?查看

五、总结

1.for语句的结构
2.while语句的结构
3.until语句的结构
4.循环控制语句

艺术系歌词下载吧