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

  • 相关阅读:
    数据库访问表的问题
    UVA 10943全加和(规律)
    POJ 2594 最小路径覆盖 + 传递闭包
    phonegap入门7 capture.captureVideo 录像
    第二部分 Linux Shell高级编程技巧——第二章 Shell工具
    C#写的光模块烧写软件
    关于java的++和操作符,你真的搞明白了吗?
    MFCATL IDispatch调度接口
    c/c++函数调用约定
    HDOJ 2955 Robberies (0/1背包)
  • 原文地址:https://www.cnblogs.com/nefu-Lc/p/9505595.html
Copyright © 2011-2022 走看看