shell腳本基礎知識梳理<六>:流程控制 while 循環語句

while語法格式

while 測試條件
do
指令
done

while循環可用於讀取鍵盤信息。下面的例子中,輸入信息被設置爲變量FILM,按<Ctrl-D>結束循環。

echo '按下 <CTRL-D> 退出'
echo -n '輸入你最喜歡的網站名: '
while read FILM
do
echo "是的!$FILM 是一個好網站"
done

#!/bin/bash
int=1
while(( $int<=5 ))
do
echo $int
let "int++"
done

實例 1

!/bin/bash
#
#$RANDOM是一個系統隨機數的環境變量
num=$((RANDOM%100))
while :
do
read -p "Please guess my number [0-99]: " number
echo $num
if [ $number -lt $num ]
then
echo "$number小於$num"
elif [ $number -gt $num ]
then
echo "$number大於$num"
elif ((number==num))
then
echo "$number等於num"
break
fi
done
執行結果
[root@localhost shell]# sh where1.sh
Please guess my number [0-99]: 24
56
24小於56
Please guess my number [0-99]: 89
56
89大於56
Please guess my number [0-99]: 56
56
56等於num

實例 2

#!/bin/bash
#
file=/etc/resolv.conf
while read -r line
#while IFS=: read -r line abc
do
echo $line
done < "$file"

while IFS=: read -r user enpass uid gid desc home shell
do
[ $uid -ge 500 ] && echo "User $user $enpass ($uid) $gid $desc $home $shell"
done < /etc/passwd

執行結果

[root@localhost shell]# sh while2.sh
; generated by /usr/sbin/dhclient-script
search localdomain
nameserver 192.168.1.1
User polkitd x (999) 998 User for polkitd / /sbin/nologin
User chrony x (998) 996 /var/lib/chrony /sbin/nologin
User www x (1000) 1000 /home/www /sbin/nologin
User saslauth x (996) 76 Saslauthd user /run/saslauthd /sbin/nologin
User mysql x (1001) 1001 /home/mysql /sbin/nologin
User zabbix x (1002) 1002 /home/zabbix /sbin/nologin
User user1 x (1003) 1003 /home/user1 /bin/bash
User user2 x (1004) 1004 /home/user2 /bin/bash
User user3 x (1005) 1005 /home/user3 /bin/bash
User user4 x (1006) 1006 /home/user4 /bin/bash
User user5 x (1007) 1007 /home/user5 /bin/bash

實例 3

#!/bin/bash
count=1
while [ $count -lt 10 ]
do
let "count+=1"
echo $count
done

i=0
while (( i !=1 ))
do
if [[ $@ = ok ]]
then
i=1
fi
done

執行結果

[root@localhost shell]# sh while3.sh ok
2
3
4
5
6
7
8
9
10

無限循環語法格式:

while :
do
command
done
或者

while true
do
command
done
或者

for (( ; ; ))

實例 4

#!/bin/bash
#
#whie--case...esac
while true
do
echo "What is your preferred scripting language?"
echo "1) bash"
echo "2) prel"
echo "3) python"
echo "4) ruby"
echo "5) I do not know !"
read -p "Pls input num: " lang
case $lang in
1) echo "you selected bash" ;;
2) echo "you selected prel" ;;
3)
echo "you selected python"
;;
4)
echo "you selected ruby"
;;
5)
echo "I do not know!"
exit
;;
esac
done

執行結果

root@localhost shell]# sh while-select.sh
What is your preferred scripting language?
1) bash
2) prel
3) python
4) ruby
5) I do not know !
Pls input num: 1
you selected bash
What is your preferred scripting language?
1) bash
2) prel
3) python
4) ruby
5) I do not know !

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章