1. 程式人生 > >Shell腳本編程之循環語句

Shell腳本編程之循環語句

for while until case

  • for
  • while
  • if
  • case

  • 1. for用法1

        for 變量 in 值1 值2 值3..;do  
                 執行語句 
        done
    • 用法2

      for 變量 `命令`;do                 #  可以引用命令執行結果
              執行語句
      done
    • 用法3

      for ((初始值;循環控制;變量變化));do
              執行語句
      done   #C語言風格的for循環用法

      for循環示例(1+2+3+..+100=?)

      #!/bin/bash
      sum=0                              # 初值為0
      for  ((i=1;i<=100;i++));do
              sum=$(( $sum + $i))    # 初值+i 並刷新sum值
      done
      echo "1+2+3+..+100=$sum"
    1. while循環,重復次數是利用一個條件來控制是否繼續執行這個語句,為了避免死循環,必須保證循環體中包含循環出口條件(存在退出狀態)

      #!/bin/bash
      sum=0
      i=1           # sum i 賦初值
      while (( i<=100));do       #進入循環體,每循環一次判斷一次i的值是否符合(( )) 的條件
              let "sum+=i"
              let "i+=2"
      done
      echo "sum=$sum"
      • 無條件循環

        while true;do
            執行語句

        done # 這個循環語句永遠不會跳出,無論什麽情況下while判斷語句都為真,都會繼續執行“執行語句”

        相反,對比while循環,until循環是“滿足條件就不執行”
        以1+2+3+..+100=?為例

        until  [ $i -gt 100];do                # 當 i 的值大於100時               sum=$(($sum+$i))
            i+$(($i+1))

        done
        echo "$sum"

    if語句,跟case比較像 ,也是條件判斷語句,邏輯比較簡單

        #!/bin/bash
        read -p "Please Enter a Number:" number           # 讀取終端輸入的數字
        if [ $number -eq 1  ];then
                echo "the number is 1 "                                    # 如果輸入數字等於 1 ,輸出此句
        elif [ $number -eq 2 ]
                echo "the number is 2 "                                    # 如果輸入數字等於 2 ,輸出此句
        elif [ $number -eq 3 ]
                echo "the number is 3"                                     # 如果輸入數字等於 2 ,輸出此句
        else
                echo "the number is greater than 3 "               # 如果輸入的數字都不滿足,則輸出此句
        fi

    case語句

        #!/bin/bash
        read -p "Please Enter a Number:" number
        case $number in
                1) echo "the number is 1";;
                2) echo "the number is 2 ";;
                3) echo "the number is 3 ";;
                *) echo "the number is greater than 3"
        esac                     # 很容易理解,而且看起來比if 簡潔一些,

    Shell腳本編程之循環語句