2018-4-19 17周2次课 for循环while循环breakcontinueexit
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了2018-4-19 17周2次课 for循环while循环breakcontinueexit相关的知识,希望对你有一定的参考价值。
20.10 for循环
·语法:for 变量名 in 条件; do …; done
案例1
计算1到100数字的和
#!/bin/bash sum=0 for i in `seq 1 100` do sum=$[$sum+$i] ##核心语句 echo $i done echo $sum
案例2
列出/etc/下的目录或子目录
#!/bin/bash cd /etc/ for a in `ls /etc/` do if [ -d $a ] then ls -d $a fi done
ls 是用空格或回车作为分隔符,for循环以他对象,那么可能会出错
20.11/20.12 while循环
·语法 while 条件; do … ; done
案例1
#!/bin/bash while : ## : 表示死循环 或者写成 while true do load=`w|head -1|awk -F 'load average: ' '{print $2}'|cut -d. -f1` if [ $load -gt 10 ] then top|mail -s "load is high: $load" [email protected] ##或/usr/local/sbin/mail.py [email protected] "load high" "$load" fi sleep 30 done
案例2
#!/bin/bash while : do read -p "Please input a number: " n if [ -z "$n" ] then echo "you need input sth." continue ## continue 指继续重新再来一遍循环 fi n1=`echo $n|sed 's/[0-9]//g'` if [ -n "$n1" ] then echo "you just only input numbers." continue ## continue 从头继续重新再来一遍循环 fi break ##退出 while 循环 done echo $n
20.13 break跳出循环
#!/bin/bash for i in `seq 1 5` do echo $i if [ $i == 3 ] ##正常等于号应该写为 -eq,字符串等于为 == then break fi echo $i done echo aaaaaaa
[[email protected] shell]# sh -x break.sh ++ seq 1 5 + for i in '`seq 1 5`' + echo 1 1 + '[' 1 == 3 ']' + echo 1 1 + for i in '`seq 1 5`' + echo 2 2 + '[' 2 == 3 ']' + echo 2 2 + for i in '`seq 1 5`' + echo 3 3 + '[' 3 == 3 ']' + break + echo aaaaaaa aaaaaaa
原本在 i 为 3 之前,脚本一直执行到done,然后在从头循环,而 为 3 时,之间break跳出循环,
echo aaaaaaa
·break 用在循环语句里,for 也行,while 也行
20.14 continue结束本次循环
·忽略continue之下的代码,直接进行下一次循环
#!/bin/bash for i in `seq 1 5` do echo $i if [ $i == 3 ] then continue fi echo $i done echo $i
[[email protected] shell]# sh -x continue.sh ++ seq 1 5 + for i in '`seq 1 5`' + echo 1 1 + '[' 1 == 3 ']' + echo 1 1 + for i in '`seq 1 5`' + echo 2 2 + '[' 2 == 3 ']' + echo 2 2 + for i in '`seq 1 5`' + echo 3 3 + '[' 3 == 3 ']' ## 等于3时,直接结束了本次循环,从头开始 + continue + for i in '`seq 1 5`' + echo 4 4 + '[' 4 == 3 ']' + echo 4 4 + for i in '`seq 1 5`' + echo 5 5 + '[' 5 == 3 ']' + echo 5 5 + echo aaaaaaa aaaaaaa
·break会跳出循环,不再执行循环,而continue会结束本次循环,从头开始执行循环
20.15 exit退出整个脚本
exit直接退出脚本:
#!/bin/bash for i in `seq 1 5` do echo $i if [ $i == 3 ] then exit fi echo $i done echo aaaaa
[[email protected] shell]# sh -x exit.sh ++ seq 1 5 + for i in '`seq 1 5`' + echo 1 1 + '[' 1 == 3 ']' + echo 1 1 + for i in '`seq 1 5`' + echo 2 2 + '[' 2 == 3 ']' + echo 2 2 + for i in '`seq 1 5`' + echo 3 3 + '[' 3 == 3 ']' + exit
以上是关于2018-4-19 17周2次课 for循环while循环breakcontinueexit的主要内容,如果未能解决你的问题,请参考以下文章