zoukankan      html  css  js  c++  java
  • 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

    人生得意须尽欢,莫使金樽空对月。 天生我材必有用,千金散尽还复来。
  • 相关阅读:
    vue父组件促发子组件中的方法
    油猴脚本:油猴脚本自动点击 | 自动检测元素并点击、休眠、顺序执行、单页面也适用
    油猴脚本:使用layer.js mobx lodash jquery
    vue项目统计src目录下代码行数
    常用mobx响应新值变化函数autorun和observe
    uni app使用mobx | uni app状态管理mobx
    File and Code Templates | webstorm代码文件模板 vue typescript
    javascript立即执行函数简单介绍
    VSCode 安装GitLens插件不生效问题
    常用的浅拷贝实现方法
  • 原文地址:https://www.cnblogs.com/heian99/p/11972304.html
Copyright © 2011-2022 走看看