while循环
适用于命题为真时执行循环的环境
命题为真时进入循环;命题为假时退出循环
或者说是条件满足时就进入循环的场景
语法格式:
while CONDITION; do
循环体
done
CONDITION:循环控制条件
进入条件:CONDITION为true;
退出条件:CONDITION为false
进入循环之前,先做一次判断;每一次循环之后会再次做判断;条件为“true”,则执行一次循环;直到条件测试状态为“false”终止循环
因此:CONDTION一般应该有循环控制变量;而此变量的值会在循环体不断地被修正
while循环应用实例:
1,计算1-100之间所有正整数的和
#!/bin/bash
#Author:wangjun
#Contact QQ:183530300
#Version:1.0
#Create time:2016-08-17 16:59:54
#Description:1-100 all positive integer‘s sum
declare -i sum=0
declare -i I=1
while [[ $I -le 100 ]];do
let sum+=$I
let I++
done
echo "1-100 all positive integer‘s sum : $sum"
2,自动扫描1-254网段的所有主机,统计在线主机数与不在线主机数
#!/bin/bash
#Author:wangjun
#Contact QQ:183530300
#Version:1.0
#Create time:2016-08-17 16:10:39
#Description:ping all host and count the number
declare -i online=0
declare -i offline=0
declare -i host=1
while [[ $host -lt 255 ]];do
ping -c 1 -W 1 10.1.250.$host &> /dev/null && echo "10.1.250.$host is online" && let online=$online+1 || let offline=$offline+1
let host=$host+1
done
echo "Online hosts number : $online"
echo "Offline hosts number : $offline"
3,生成10个随机数,并找出最大随机数和最小随机数
#!/bin/bash
#Author:wangjun
#Contact QQ:183530300
#Version:1.0
#Create time:2016-08-17 20:22:58
#Description:random number comparative
minrandom=$RANDOM
maxrandom=$minrandom
declare -i R=1
echo $minrandom
while [[ $R -le 9 ]];do
RD=$RANDOM
echo $RD
if [[ $RD -gt $maxrandom ]];then
maxrandom=$RD
elif [[ $RD -lt $minrandom ]];then
minrandom=$RD
fi
let R++
done
echo "Minrandom is : $minrandom"
echo "Maxrandom is : $maxrandom"
4,打印九九乘法表
#!/bin/bash
#Author:wangjun
#Version:1.0
#Contact QQ:183530300
#Create time:2016-08-16 20:12:30
#Description:99 multiplication table
declare -i Row=1
declare -i Column=1
while [ "$Row" -lt 10 ];do
while [ "$Column" -le "$Row" ];do
echo -ne "${Column}x${Row}=$[$Column*$Row]\t"
let Column++
done
Column=1
let Row++
echo
done
5,每隔3秒钟查询系统上已经登录的用户信息,如果发现hacker用户登录,则将登录时间和主机记录于日志/var/log/login.log中,并提示hacker用户退出系统
#!/bin/bash
#Author:wangjun
#Contact QQ:183530300
#Version:1.0
#Create time:2016-08-18 08:14:07
#Description:Monitor whether the hacker user has loggedon
while !(who | grep "^hacker\>");do
echo -e "`date +%T`\thacker user doesn‘t logged on"
sleep 3
done
echo -e "`date +%T`\thacker user logged on" | tee /var/log/login.log
echo "Please exit current system" | write hacker
本文出自 “爱情防火墙” 博客,请务必保留此出处http://183530300.blog.51cto.com/894387/1840655
原文地址:http://183530300.blog.51cto.com/894387/1840655