温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-06-15 14:07:08 来源:网络 阅读:202 作者:wx5cb5dcd871bbc 栏目:系统运维

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 !

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI