while循环和until :循环次数不定。

一、while循环

1、格式:


while 条件测试;do


 循环体;


done


例:用while求1-100内的所有正整数的和。


#!/bin/bash


declare -i sum=0,i=1


while [ $i -le 100 ];do

let sum+=$i

let i++

done 


echo $sum



例:用while求1-100内的所有偶数的和。


#!/bin/bash


declare -i sum=0,i=2


while [ $i -le 100 ];do

let sum+=$i

let i+=2

done 


echo $sum



例:通过键盘提示用户输入字符,将用户输入的小写字母转换为大写,

    转换一次之后,再次提醒用户输入,再次转换,直到输入quit,

    quit表示退出。



#!/bin/bash


read -p "Enter a word:" word


while [[ "$word" != "quit" ]];do

     echo $word |tr 'a-z' 'A-Z'

     read -p "Enter a word again:" word

done



例:提示用户输入一个用户名,如果存在,显示用户UID和SHELL信息,否则,则显示无此用户;

    显示完成后,提示用户再次输入;如果是quit则退出。


#!/bin/bash


read -p "Enter a username:" userName


while [[ "$userName" != "quit" ]];do

if id $userName &> /dev/null;then

   grep "^$userName\>" /etc/passwd |cut -d : -f3,7

 else 

   echo "$userName is not exist."   

fi


read -p "Enter a username again:" userName

done



例:提示用户输入一个用户名,

   如果不存在,提示用户再次输入。

   如果存在,则判定用户是否登录,

   如果未登录,提示“$userName is not here.”,

   则停止5秒钟,再次判断用户是否登录,

   直到用户登录系统,显示“$userName is on”。



#!/bin/bash


read -p "Enter a user name:" userName


while ! id $userName &>/dev/null;do

read -p "Enter a user name again:" userName

done



while ! who | grep "^$userName" &>/dev/null ;do

echo "$userName is not here."

sleep 5

done


echo "$userName is on."


二、until循环:条件不满足,则循环,否则退出(可见于while相反)。


例:用untile循环,求100以内所有正整数之和。


#!/bin/bash


declare -i sum=0


declare -i i=1


untile [ $i -gt 100 ];do

    let sum+=$i

    let i++

done


echo $sum



三、组合条件测试:


1、逻辑与:

  [ condition1 ] && [ condition2 ]

  [ condition1 -a condition2 ]

  [[ condition1 && condition2 ]]

 

注意:&&只能用于双括号 ` `中.


2、逻辑或:


  [ condition1 ] || [ condition2 ]

  [ condition1 -o condition2 ]

  [[ condition1 || condition2 ]]

 

注意:||只能用于双括号 ` `中.


3、使用while循环一次读取文件的一行,直到文件尾部;

while read line ;do


循环体 


done </path/to/somefile



例:取出当前系统上,默认shell为bash的用户


#!/bin/bash


while read line;do


  [[ `echo $line |cut -d: -f7` == "/bin/bash" ]] && echo $line |cut -d: -f1


done </etc/passwd


五、循环控制continue和break:


1、continue提前结束本次循环而开始下一轮循环。


如:求100之内所有偶数之和。

#!/bin/bash


declare -i evenSum=0

declare -i i=1


while [ $i -le 100 ] ;do

    if [ [$i%2] -eq 1 ];then

let i++

continue

    else

    let evenSum+=$i

    let i++

     fi

done



2、break [n]:跳出当前循环,n跳出基层循环(循环嵌套时)。