while 条件 ;do
循环体
done
break:提前退出循环
continue:提前结束本轮循环,而进入下一轮循环(条件满足即结束)
#!/bin/bash # let SUM=0 let I=0 while [ $I -lt 100 ];do let I++ if [ $[$I%2] -eq 1 ];then continue fi let SUM+=$I done echo $SUM
[root@localhost tmp]# cat while.sh #!/bin/bash # let sum=0 let I=0 while [ $I -le 100 ];do if [ $[$I%2] -eq 0 ];then let sum+=$I fi let I++ done echo $sum [root@localhost tmp]# cat sum.sh #!/bin/bash # declare SUM=0 declare I=0 for ((I=0;I<=100;I+=2));do let sum+=$I done echo $sum
break的用法:
#!/bin/bash # declare -i SUM=0 for I in {1..1000};do let SUM+=$I if [ $SUM -gt 5000 ];then break fi done echo $I echo $SUM
while的特殊用法一、
while死循环,利用break机制退出:
#!/bin/bash # while :;do read -p "Enter your file path: " FILEPATH [ $FILEPATH == ‘quit‘ ] && break if [ -e $FILEPATH ];then echo "$FILEPATH exists." else echo "$FILEPATH not exists." fi done echo "Quiting"
while的特殊用法二、
while read LINE;do
done < /path/to/somefile
#!/bin/bash # let I=0 while read LINE;do USER=`echo $LINE | grep "/bin/bash" | cut -d: -f1` echo $USER | sed /^$/d let I++ [ $I -gt 1 ] && break done < /etc/passwd
#!/bin/bash FILE=/etc/passwd let I=0 while read LINE;do [ `echo $LINE | awk -F: ‘{print $3}‘` -lt 500 ] && continue [ `echo $LINE | awk -F: ‘{print $NF}‘` == ‘/sbin/nologin‘ ] && echo $LINE | awk -F: ‘{print $1}‘ && let I++ [ $I -ge 6 ] && break done < $FILE
脚本示例
1、判断一个指定的bash脚本是否有语法错误,如果有错误,则提醒用户键入Q或者q无视错误退出,其它任何键可以通过vim打开这个指定的脚本;
2、如果用户通过vim打开编辑后保存退出时仍然有错误,刚重复第一步中的内容,否则就正常关闭退出
#!/bin/bash # until bash -n $1 &>/dev/null;do read -p "Syntax error wrong. Enter Q|q quit,other keywords for editing: " CHOICE case $CHOICE in Q|q) echo "Syntax error wrong. quiting!" exit 9 ;; *) vim + $1 ;; esac done
本文出自 “魏镇坪” 博客,请务必保留此出处http://leozhenping.blog.51cto.com/10043183/1643060
原文地址:http://leozhenping.blog.51cto.com/10043183/1643060