• while循环语句


    while条件句:条件满足一直执行。

    语法:

    while 条件

      do

      指令

    done

    untile条件句:条件满足就退出(不常用了解)

    until 条件

      do

      指令

    done

    案例一:每隔2秒查看下服务器的负载相当于top命令

    [root@www while]# cat while1.sh
    #!/bin/bash
    while true
    do
    uptime
    sleep 2
    done

    #while true 表示永久为真,一直执行,死循环(守护进程)。

    执行结果:

    10:53:06 up 18:37,  2 users,  load average: 0.08, 0.23, 0.14

    案例二:

    #!/bin/bash
    while true
    do
    uptime >> /root/while/test.log
    # usleep 500 #微秒
    usleep 10000000
    done

    扩展:

    后台执行的方法:

    [root@www while]# sh while2.sh &
    [1] 54786

    查看后台正在运行的进程

    [root@www while]# jobs
    [1]+ Running sh while2.sh &

    将后台运行的放到前台执行

    [root@www while]# fg 1
    sh while2.sh

    将一个后台运行的脚本使用fg 1放到前台运行,然后ctrl+z暂停,然后jobs查看。最后bg 1放在后台执行。然后fg1放到前台执行,最后ctrl+c停止。

     

    while循环:计算从1+100总和

    #!/bin/bash
    i=1
    sum=0
    while ((i <= 100))
    do
    ((sum=sum+i))
    ((i++))
    done
    echo $sum

    [ -n "$sum" ] && printf "totalsum is: $sum "

    [ -n num ]:字符串不为空为真。

    数字1到10正向反向打印

    反向打印:

    #!/bin/bash
    i=10
    while ((i>0))
    do
    echo $i
    ((i--))
    done

    正向打印

    i=1
    while ((i<=10))
    do
    echo $i
    ((i++))
    done

    正向打印

    i=1
    #while [ $i -le 10 ]
    while [[ i -le 10 ]]
    do
    echo $i
    ((i++))
    done

    #使用read读取数字,然后逐个减一。

    read -t10 -p "please input the number: " i
    while ((i--))
    do
    echo $i

    done

    #通过脚本传递参数的方式(反向打印)

    i="$1"
    while [ $i -gt 0 ]
    do
    echo $i
    ((--i))
    done

    untile命令:条件满足退出(正反打印)

    #!/bin/bash
    i=1
    until ((i>10))
    do
    echo "$i"
    ((sun=sum+i))
    ((i++))
    done

    i=10
    until ((i<=0))
    do
    echo "$i"
    ((sun=sum+i))
    ((i--))
    done

    while正式实例

    使用curl检测一个网站状态是否为200

    #!/bin/bash
    while true
    do
    status=`curl -I -s --connect-timeout 10 $1|head -1|cut -d " " -f 2`
    if [ "$status" == "200" ];then
    echo "this url is ok !"
    else
    echo "this url is no !"
    fi
    sleep 2
    done

    升级版本

    #!/bin/bash
    . /etc/rc.d/init.d/functions
    while true
    do
    status=`curl -I -s --connect-timeout 10 $1|head -1|cut -d" " -f 2`
    if [ "$status" = "200" ];then
    action "nginx this is yes !" /bin/true
    else
    action "nginx this is no !" /bin/false
    fi
    sleep 2
    done

  • 相关阅读:
    我看到的我未曾是你们看到的我。
    nagios状态数据更新不及时问题
    Ubuntu下安装 nagiosgraph报错处理
    禁止、允许PING
    windows批量关机
    [转载]div仿框架(B/S结构软件界面)详解[非quirks模式全兼容]
    rrdtool错误attempt to put segment in horiz list twice
    命令参考大全 iostat
    SAP学习手册
    顾问成长之路
  • 原文地址:https://www.cnblogs.com/xiaoyongzhuo/p/7417549.html
Copyright © 2020-2023  润新知