shell中的while迴圈例項
1.利用while迴圈計算1到100的和:
示例程式碼1:
#!/bin/bash
i=1
sum=0
while [ $i -le 100 ]
do
let sum=sum+$i
let i++
done
echo $sum
示例程式碼2:利用while迴圈計算1到100之間所有奇數之和
#!/bin/bash
i=1
sum=0
while [ $i -le 100 ]
do
let sum=sum+$i
let i+=2
done
echo $sum
示例程式碼3:利用while迴圈計算1到100之間所有偶數之和
#!/bin/bash
i=2
sum=0
while [ $i -le 100 ]
do
let sum=sum+$i
let i+=2
done
echo $sum
2.利用while迴圈列印**
示例程式碼:利用while迴圈列印一個5x5的*
#!/bin/bash
i=1
j=1
while [ $i -le 5 ]
do
while [ $j -le 5 ]
do
echo -n "* "
let j++
done
echo
let i++
let j=1
done
3.使用read結合while迴圈讀取文字檔案:
示例程式碼1:
#!/bin/bash
file=$1 #將位置引數1的檔名複製給file
if [ $# -lt 1 ];then #判斷使用者是否輸入了位置引數
echo "Usage:$0 filepath"
exit
fi
while read -r line #從file檔案中讀取檔案內容賦值給line(使用引數r會遮蔽文字中的特殊符號,只做輸出不做轉譯)
do
echo $line #輸出檔案內容
done < $file
示例2:按列讀取檔案內容
#!/bin/bash
file=$1
if [[ $# -lt 1 ]]
then
echo "Usage: $0 please enter you filepath"
exit
fi
while 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
;;
esac
done