• Linux shell while循环语句


    for :明确循环次数
    while :不确定循环换次数

    while循环

    (1)

    while CONDITION;do
          statement
          statement
          <改变循环条件真假的语句>
    done

    编写脚本,计算1--100的和

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


    编写while循环,输入q退出(不输入q,不退出)

    #!/bin/bash
    #
    read -p "请输入你的选择:" choice
    
    while [ $choice != q  ];do
        echo -e "33[31m输入错误33[0m" #加的颜色代码
        read -p "请输入你的选择:" choice
    done


    (2)

    while true;do
          statement
          statement
          <break退出>
    done

     

    编写while循环,输入q退出(不输入q,不退出)

    #/bin/bash
    #
    while true;do
        read -p "请输入你的选择" str
        echo "输入错误"
        if [ $str == q ];then
            break
        fi
    done

    编写脚本,每4秒查看系统的内存

    #!/bin/bash
    #
    while true;do
        uptime
        sleep 3
    done


    (3)

    while read line;do
        statement
        statement
    done < file


    编写脚本,向系统每个用户打招呼

    v#!/bin/bash
    #
    while read line;do
        sh_name=$(echo $line | awk -F: '{print $1}')
        echo "Hello $sh_name"
    
    done < /etc/passwd


    编写脚本,统计/bin/bash /sbin/nologin的个数

    [root@wei while]# cat 6.sh 
    #!/bin/bash
    #
    bash_number=0
    nologin_number=0
    
    while read line;do
        sh_name=$(echo $line | awk -F: '{print $7}')
        case $sh_name in
            /bin/bash)
                let bash_number=$bash_number+1
                ;;
            /sbin/nologin)
                let nologin_number=$nologin_number+1
                ;;
        esac
    
    done < /etc/passwd
    
    echo "bash用户数量:$bash_number"
    echo "nologin_number用户数量:$nologin_number"

    执行效果

    [root@wei while]# ./6.sh 
    bash用户数量:17
    nologin_number用户数量:17


    util循环:

    util CONDITION;do
        statement
        statement
    done

    条件为假时,执行循环,条件为真时,结束循环


    重点掌握

    if,case

    for,while

    人生得意须尽欢,莫使金樽空对月。 天生我材必有用,千金散尽还复来。
  • 相关阅读:
    完全分布式安装HBase
    HDFS常用的文件API操作
    启动HBase后遇到的一个问题
    HBase常用的数据库API操作
    HBase数据库常用操作命令
    Hive安装
    eclipse中配置hadoop开发环境
    Hadoop小程序倒排索引
    我学习设计模式的一些所想所得
    架构之路实战项目记录(二) 忘记数据库 开始抽象
  • 原文地址:https://www.cnblogs.com/heian99/p/11972304.html
Copyright © 2020-2023  润新知