While循環的格式:
while expression do command command 、、、 done
1、計數器控制的while循環:
主要用於已經准確知道要輸入的數據和字符串的數目。
例子:
#!/bin/bash int=1 while (($int <=5 )) do echo $int let "int++" done
2、結束標記控制的while循環
主要用於不知道讀入數據的個數,但是可以設置一個特殊的數據值來結束循環,該特殊值稱為結束標記,通過提示用戶輸入進行操作。
例子:
#!/bin/bash #用腳本演示使用結束標記控制while循環實現猜1~10內的數 echo "Please input the num (1~~10): " read num while [[ $num != 4 ]] do if [ $num -lt 4 ];then echo "Too small,Try again.." read num elif [ $num -gt 4 ];then echo "Too big,Try again.." read num else exit 0 fi done echo "Yes,you are right !!"
3、標志控制的while循環
用戶輸入標志值來控制循環的結束
例子:
#!/bin/bash echo "Please input the num: " read num sum=0 i=1 signal=0 #while [[ $signal != 1 ]] while (($signal != 1)) do if [ $i -eq $num ];then let "signal=1" let "sum+=i" echo "1+2、、、+$num=$sum" else let "sum=sum+i" let "i++" fi done
4、命令行控制的while循環
例子:
#!/bin/bash echo "Please iput arguements is $# " echo "What you input : " while [[ $* != "" ]] do echo $1 shift done