您好,登錄后才能下訂單哦!
while語法格式
while 測試條件
do
指令
donewhile循環可用于讀取鍵盤信息。下面的例子中,輸入信息被設置為變量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
donei=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 !
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。