shell脚本基础知识梳理<六>:流程控制while循环语句

while语法格式

创新互联公司成都网站建设定制设计,是成都网站营销推广公司,为凿毛机提供网站建设服务,有成熟的网站定制合作流程,提供网站定制设计服务:原型图制作、网站创意设计、前端HTML5制作、后台程序开发等。成都网站改版热线:18982081108

while 测试条件
do
指令
done

while循环可用于读取键盘信息。下面的例子中,输入信息被设置为变量FILM,按结束循环。

echo '按下 退出'
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 !


名称栏目:shell脚本基础知识梳理<六>:流程控制while循环语句
网站链接:http://cdiso.cn/article/pegeed.html

其他资讯