2023年7月10日发(作者:)
c语⾔while与until的⽤法,while和until循环while循环和until :循环次数不定。⼀、while循环1、格式:while 条件测试;do循环体;done例:⽤while求2021年05⽉19⽇0内的所有正整数的和。#!/bin/bashdeclare -i sum=0,i=1while [ $i -le 100 ];dolet sum+=$ilet i++doneecho $sum例:⽤while求2021年05⽉19⽇0内的所有偶数的和。#!/bin/bashdeclare -i sum=0,i=2while [ $i -le 100 ];dolet sum+=$ilet i+=2doneecho $sum例:通过键盘提⽰⽤户输⼊字符,将⽤户输⼊的⼩写字母转换为⼤写,转换⼀次之后,再次提醒⽤户输⼊,再次转换,直到输⼊quit,quit表⽰退出。#!/bin/bashread -p "Enter a word:" wordwhile [[ "$word" != "quit" ]];doecho $word |tr 'a-z' 'A-Z'read -p "Enter a word again:" worddone例:提⽰⽤户输⼊⼀个⽤户名,如果存在,显⽰⽤户UID和SHELL信息,否则,则显⽰⽆此⽤户;显⽰完成后,提⽰⽤户再次输⼊;如果是quit则退出。#!/bin/bashread -p "Enter a username:" userNamewhile [[ "$userName" != "quit" ]];doif id $userName &> /dev/null;thengrep "^$userName>" /etc/passwd |cut -d : -f3,7elseecho "$userName is not exist."firead -p "Enter a username again:" userNamedone例:提⽰⽤户输⼊⼀个⽤户名,如果不存在,提⽰⽤户再次输⼊。如果存在,则判定⽤户是否登录,如果未登录,提⽰“$userName is not here.”,则停⽌5秒钟,再次判断⽤户是否登录,直到⽤户登录系统,显⽰“$userName is on”。#!/bin/bashread -p "Enter a user name:" userNamewhile ! id $userName &>/dev/null;doread -p "Enter a user name again:" userNamedonewhile ! who | grep "^$userName" &>/dev/null ;doecho "$userName is not here."sleep 5doneecho "$userName is on."⼆、until循环:条件不满⾜,则循环,否则退出(可见于while相反)。例:⽤untile循环,求100以内所有正整数之和。#!/bin/bashdeclare -i sum=0declare -i i=1untile [ $i -gt 100 ];dolet sum+=$ilet i++doneecho $sum三、组合条件测试:1、逻辑与:[ condition1 ] && [ condition2 ][ condition1 -a condition2 ][[ condition1 && condition2 ]]注意:&&只能⽤于双括号 ` `中.2、逻辑或:[ condition1 ] || [ condition2 ][ condition1 -o condition2 ][[ condition1 || condition2 ]]注意:||只能⽤于双括号 ` `中.3、使⽤while循环⼀次读取⽂件的⼀⾏,直到⽂件尾部;while read line ;do循环体done例:取出当前系统上,默认shell为bash的⽤户#!/bin/bashwhile read line;do[[ `echo $line |cut -d: -f7` == "/bin/bash" ]] && echo $line |cut -d: -f1done五、循环控制continue和break:1、continue提前结束本次循环⽽开始下⼀轮循环。如:求100之内所有偶数之和。#!/bin/bashdeclare -i evenSum=0declare -i i=1while [ $i -le 100 ] ;doif [ [$i%2] -eq 1 ];thenlet i++continueelselet evenSum+=$ilet i++fidone2、break [n]:跳出当前循环,n跳出基层循环(循环嵌套时)。
发布者:admin,转转请注明出处:http://www.yc00.com/xiaochengxu/1688987065a191920.html
评论列表(0条)