1.利用while循環計算1到100的和:
示例代碼1:
#!/bin/bashi=1sum=0while [ $i -le 100 ]do let sum=sum+$i let i++doneecho $sum
示例代碼2:利用while循環計算1到100之間所有奇數之和
#!/bin/bashi=1sum=0while [ $i -le 100 ]do let sum=sum+$i let i+=2doneecho $sum
示例代碼3:利用while循環計算1到100之間所有偶數之和
#!/bin/bashi=2sum=0while [ $i -le 100 ]do let sum=sum+$i let i+=2doneecho $sum
2.利用while循環打印**
示例代碼:利用while循環打印一個5x5的*
#!/bin/bashi=1j=1while [ $i -le 5 ]do while [ $j -le 5 ] do echo -n "* " let j++ done echo let i++ let j=1done
3.使用read結合while循環讀取文本文件:
示例代碼1:
#!/bin/bashfile=$1 #將位置參數1的文件名復制給fileif [ $# -lt 1 ];then #判斷用戶是否輸入了位置參數 echo "Usage:$0 filepath" exitfiwhile read -r line #從file文件中讀取文件內容賦值給line(使用參數r會屏蔽文本中的特殊符號,只做輸出不做轉譯)do echo $line #輸出文件內容done < $file
示例2:按列讀取文件內容
#!/bin/bashfile=$1if [[ $# -lt 1 ]]then echo "Usage: $0 please enter you filepath" exitfiwhile read -r f1 f2 f3 #將文件內容分為三列do echo "file 1:$f1 ===> file 2:$f2 ===> file 3:$f3" #按列輸出文件內容done < "$file"
4.while循環中的死循環:
示例:利用死循環,讓用戶做選擇,根據客戶的選擇打印相應結果
#!/bin/bash#打印菜單while :do echo "********************" echo " menu " echo "1.tima and date" echo "2.system info" echo "3.uesrs are doing" echo "4.exit" echo "********************" read -p "enter you choice [1-4]:" choice#根據客戶的選擇做相應的操作 case $choice in 1) echo "today is `date +%Y-%m-%d`" echo "time is `date +%H:%M:%S`" read -p "press [enter] key to continue..." Key #暫停循環,提示客戶按enter鍵繼續 ;; 2) uname -r read -p "press [enter] key to continue..." Key ;; 3) w read -p "press [enter] key to continue..." Key ;; 4) echo "Bye!" exit 0 ;; *) echo "error" read -p "press [enter] key to continue..." Key ;; esacdone
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對武林網的支持。如果你想了解更多相關內容請查看下面相關鏈接
|
新聞熱點
疑難解答