while语句的使用

来源:互联网 发布:歼20 f35知乎 编辑:程序博客网 时间:2024/06/08 12:18

while语句

循环执行将某代码次数事先已知重复运行多少次?    循环次数事先已知    循环次数事先未知    必须有进入条件和退出条件函数:结构化变成及代码重用

while循环:

while CONDITION;do    循环体donecondition:循环控制条件;进入讯体之前,先做一次判断;每一次循环之后再次做判断;    条件为真,则执行一次循环;知道条件测试状态为FALSE终止循环;因此:condition一般应该有循环控制变量;而此变量的至会在循环体不断地被修正;

示例:求100以内所有正整数之和

#!/bin/bash#declare -i sum=0declare -i i=1while [ $i -le 100 ];do    let sum+=$i    let i++done

练习:
1、添加10个用户

#!/bin/bash#declare -i user=1while [ "$user" -le 10 ] ;do    if !id user$user &> /dev/null;then            useradd user$user            echo "user$user" |passwd --stdin user$user    else            echo "The user$user has saved"    fi    let user++    doneecho "FINISHED"

2、通过ping命令探测172.16.250.1-254范围内的所有主机的在线状态

#/bin/bash#num=1net=172.18.250uphosts=0downhosts=0while [ $num -le 254 ];do    ping -c 1 -w 1 $net.$num &>/dev/null    if [ $? -eq 0 ];then            echo "$net.$num is up"            let uphosts++    else            echo "$net.$num is down"            let downhosts++    fi    let num++doneecho "Uphosts $uphosts"

3、打印九九乘法表
方法一

#!/bin/bash#declare -i i=1declare -i j=1while [ $j -le 9 ];do    while [ $i -le $j ];do    echo -n -e "$i*$j=$[$i*$j]\t"    let i++    done    echo    let i=1    let j++done

方法二:

#!/bin/bash#for j in {1..9};do    for i in $(seq 1 $j);do            echo -e -n "$i*$j=$[$i*$j]\t"    done    echo done

4、利用RANDOM生成10个随机数字,输出这个10数字,并显示其中的最大和最小者

#!/bin/bash#declare -i max=0declare -i min=0declare -i i=1rand=$RANDOMmax=$randmin=$randwhile [ $i -le 9 ];do    rand=$RANDOM    echo $rand    if [ $rand -gt $max ];then            man=$rand    fi    if [ $rand -lt $min ];then            min=$rand    fi    let i++doneecho "Max:$max"echo "Min:$min"
原创粉丝点击