基础格式
while循环语法: while [ 条件判断式 ] do 程序 done
只要条件成立就反复执行命令,直到命令不成立
案例
无限循环(又名死循环)
#!/bin/bash while true do echo hehe done
设定限制
#!/bin/bash i=0 while [ $i -le 10 ] do echo hehe let i++ done
输出10~1的降序两列,并得出和
#!/bin/bash i=10 while [ $i -gt 0 ] do sum=$(( $i + $i )) echo $i + $i = $sum let i-- done
输出10的升序和降序之和
#!/bin/bash a=1 b=10 while [ $a -le 10 ] do sum=$(( $a + $b )) echo $a + $b = $sum let a++ let b-- done
批量创建用户
#!/bin/bash while read user do id $user &> /dev/null if [ $? -eq 0 ];then echo "useradd: $user already exsits" else useradd $user &> /dev/null echo "user:$user create successful" fi echo $user sleep 1 done<user.txt
内置跳出循环命令
exit 跳出脚本,剩余代码都不执行
break 跳出循环,会执行循环后的代码
continue 结束本次循环,继续下次循环,包括循环后代码
案例1:exit vim test1.sh #!/bin/bash for i in {1..3} do echo "123" exit echo "456" done echo "done..." 案例2:break vim test2.sh #!/bin/bash for i in {1..3} do echo "123" break echo "456" done echo "done..." 案例3:continue vim test3.sh #!/bin/bash for i in {1..3} do echo "123" continue echo "456" done echo "done..."