zoukankan      html  css  js  c++  java
  • Linux的bash脚本编程(if语句和循环语句)

    if语句

      CONDITION:

        bash命令:

          用命令的执行状态结果:

            成功:true

            失败:false

          成功或失败的意义:取决于用到的命令

      单分支:

        if CONDITION;then

          if-true

        fi

      分支:

        if CONDITION;then

          if-true

        else

          if-false

        fi

      多分支:

        if CONDITION;then

          if-true

        elif CONDITION2;then

          if-true

        elif CONDITION3;then

          if-true

        ……

        else

          all-false

        fi

    循环:for

      for循环:

        for 变量名  in 列表 ; do

          循环体

        done

        执行机制:

          依次将列表中的元素赋值给“变量名”

        示例:添加10个用户,user1-user10,密码同用户名

          #!/bin/bash

          #

          if [ !$UID - eq 0 ]; then  

            echo "Only root"

            exit 1

          fi

          for i in {1...10}; do

            if id user$i & > /dev/null; then

            echo "user$i exists"

            else

              useradd user$i

            if [$? - eq 0 ]; then

              echo "user$i" | passwd --stdin user$i &> /dev/null

                echo "Add user$i finished"

              fi

            fi

          done

    列表的生成方式:

      (1)直接给出列表

      (2)整数列表

        {start..end}

        $(seq [start [step ] ]  end)

      (3)返回列表的命令

      (4)glob

      (5)变量引用

        $@,$*

      示例:判断某路径下的所有文件类型

        #! /bin/bash

        #

        for file in $(ls /var); do

          if [ -f /vvar/$file ]; then

          echo "Common file"

          elif [ -L /var/$file ]; then

          echo "Symbolic file"

          elif [ -d /var/$file ]; then 

          echo "Directory"

          else

          echo "Other type"

          fi

        done

  • 相关阅读:
    UTF8编码的空格(194 160)问题
    经典sql语句大全
    Workflow 4.0 中三种方式实现workflow的触发调用
    VS2010 常用快捷键
    JS验证密码安全级别
    JS零散知识记录
    MVC project on VS2010 error : The project type is not supported by this installation
    解决IronPython没有三元运算符的问题
    何时何地不能使用泛型
    今天写的代码,可惜没有用上,但想想可能以后还能用上吧。
  • 原文地址:https://www.cnblogs.com/nefu-Lc/p/9505595.html
Copyright © 2011-2022 走看看