next up previous contents
Next: 迴圈 (loop) Up: Shell scripts - 條件判斷與迴圈 Previous: Shell scripts - 條件判斷與迴圈   Contents

條件判斷式

  • if .... then:當符合條件判斷時,就進行某項工作。
    1. 語法一:
      if [ 條件判斷式 ]; then
              當條件判斷式成立時,可以進行的指令工作內容;
      fi
      
    2. 條件判斷式的判斷方法:
      && 代表 AND; 
      || 代表 OR;
       
      [root@linux scripts]# vi sh06-2.sh
      #!/bin/bash
      # Program:
      #       This program will show the user's choice
      # History:
      # 2005/08/25    csie   First release
      
      read -p "Please input (Y/N): " yn
      
      if [ "$yn" == "Y" ] || [ "$yn" == "y" ]; then
              echo "OK, continue"
              exit 0
      fi
      if [ "$yn" == "N" ] || [ "$yn" == "n" ]; then
              echo "Oh, interrupt!"
              exit 0
      fi
      echo "I don't know what is your choise" && exit 0
      
    3. 語法二:
      if [ 條件判斷式 ]; then
              當條件判斷式成立時,可以進行的指令工作內容;
      else
              當條件判斷式不成立時,可以進行的指令工作內容;
      fi
      
    4. 語法三:
      if [ 條件判斷式一 ]; then
              當條件判斷式一成立時,可以進行的指令工作內容;
      elif [ 條件判斷式二 ]; then
              當條件判斷式二成立時,可以進行的指令工作內容;
      else
              當條件判斷式一與二均不成立時,可以進行的指令工作內容;
      fi
      
    5. 例題:改寫sh06-2.sh:
      [root@linux scripts]# vi sh06-3.sh
      #!/bin/bash
      # Program:
      #       This program will show the user's choice
      # History:
      # 2005/08/25    csie   First release
      
      read -p "Please input (Y/N): " yn
      
      if [ "$yn" == "Y" ] || [ "$yn" == "y" ]; then
              echo "OK, continue"
      elif [ "$yn" == "N" ] || [ "$yn" == "n" ]; then
              echo "Oh, interrupt!"
      else
              echo "I don't know what is your choise"
      fi
      
    6. 例題:偵測輸入的參數是否為 hello。
      1. 如果是,顯示 "Hello, how are you ?";
      2. 如果沒有加任何參數,提示使用者必須要使用的參數下達法;
      3. 而如果加入的參數不是 hello ,就提醒使用者僅能使用 hello 為參數。
      [root@linux scripts]# vi sh08.sh
      #!/bin/bash
      # Program:
      #       Show "Hello" from $1....
      # History:
      # 2005/08/28    csie   First release
      
      if [ "$1" == "hello" ]; then
              echo "Hello, how are you ?"
      elif [ "$1" == "" ]; then
              echo "You MUST input parameters, ex> $0 someword"
      else
              echo "The only parameter is 'hello'"
      fi
      
    7. 利用『 netstat -tuln 』可取得目前主機啟動的服務,其中 Local Address 冒號( : )後為 port。
      [root@linux ~]# netstat -tuln
      Active Internet connections (only servers)
      Proto Recv-Q Send-Q Local Address   Foreign Address    State
      tcp        0      0 0.0.0.0:199     0.0.0.0:*          LISTEN
      tcp        0      0 :::80           :::*               LISTEN
      tcp        0      0 :::22           :::*               LISTEN
      tcp        0      0 :::25           :::*               LISTEN
      
      # 常見的 port 與相關網路服務的關係: 
      80: WWW 
      22: ssh 
      21: ftp 
      25: mail
      
      # netstat  [address_family_options]  [--tcp|-t]   [--udp|-u]
      [--raw|-w]       [--listening|-l] [--all|-a] [--numeric|-n]
      [--numeric-hosts][--numeric-       ports][--numeric-ports]
      [--symbolic|-N]    [--extend|-e[--extend|-e]]  [--timers|-o]
      [--program|-p] [--verbose|-v] [--continuous|-c] [delay]
      
    8. 例題:如何透過 netstat 偵測主機是否有開啟 80: WWW, 22: ssh, 21: ftp, 25: mail 四個主要的網路服務埠口?
      [root@linux scripts]# vi sh09.sh
      #!/bin/bash
      # Program:
      #       Using netstat and grep to detect WWW,SSH,FTP and Mail services.
      # History:
      # 2005/08/28    csie   First release
      
      # 1. 先作一些告知的動作
      echo "Now, the services of your Linux system will be detect!"
      echo -e "The www, ftp, ssh, and mail will be detect! \n"
      
      # 2. 開始進行一些測試的工作,並且也輸出一些資訊。
      testing=`netstat -tuln | grep ":80 "`
      if [ "$testing" != "" ]; then
              echo "WWW is running in your system."
      fi
      testing=`netstat -tuln | grep ":22 "`
      if [ "$testing" != "" ]; then
              echo "SSH is running in your system."
      fi
      testing=`netstat -tuln | grep ":21 "`
      if [ "$testing" != "" ]; then
              echo "FTP is running in your system."
      fi
      testing=`netstat -tuln | grep ":25 "`
      if [ "$testing" != "" ]; then
              echo "Mail is running in your system."
      fi
      
    9. 例題:計算畢業日期還剩幾天?
      1. 先讓使用者輸入他們的畢業日期;
      2. 再由現在日期比對畢業日期;
      3. 由兩個日期的比較來顯示『還需要幾天』才能夠畢業的字樣。
      [root@linux scripts]# vi sh10.sh
      #!/bin/bash
      # Program:
      #       Tring to calculate your graduation date at how many days 
      #       later...
      # History:
      # 2005/08/29    csie   First release
      
      # 1. 告知使用者這支程式的用途,並且告知應該如何輸入日期格式?
      echo "This program will try to calculate :"
      echo "How many days about your graduation date..."
      read -p "Please input your graduation date (YYYYMMDD ex>20050401): " date2
      
      # 2. 測試輸入的內容是否正確?利用正規表示法
      date_d=`echo $date2 |grep '[0-9]\{8\}'`
      if [ "$date_d" == "" ]; then
              echo "You input the wrong format of date...."
              exit 1
      fi
      
      # 3. 開始計算日期
      declare -i date_dem=`date --date="$date2" +%s`
      declare -i date_now=`date +%s`
      declare -i date_total_s=$(($date_dem-$date_now))
      declare -i date_d=$(($date_total_s/60/60/24))
      if [ "$date_total_s" -lt "0" ]; then
              echo "You had been graduation before: " $((-1*$date_d)) " ago"
      else
              declare -i date_h=$(($(($date_total_s-$date_d*60*60*24))/60/60))
              echo "You will be demobilized after $date_d days and $date_h hours."
      fi
      
  • case ..... esac 判斷
    1. 語法:
      case $變數名稱 in
        "第一個變數內容")
              程式段
              ;;   ###兩個分號 (;;) 來代表該程式段落的結束
        "第二個變數內容")
              程式段
              ;;
        *)
              不包含第一個變數內容與第二個變數內容的其他程式執行段
              exit 1
              ;;
      esac
      
    2. 改寫 sh08.sh
      [root@linux scripts]# vi sh08-2.sh
      #!/bin/bash
      # Program:
      #       Show "Hello" from $1.... by using case .... esac
      # History:
      # 2005/08/29    csie   First release
      
      case $1 in
        "hello")
              echo "Hello, how are you ?"
              ;;
        "")
              echo "You MUST input parameters, ex> $0 someword"
              ;;
        *)
              echo "Usage $0 {hello}"
              ;;
      esac
      
    3. 例題:讓使用者能夠輸入 one, two, three,並且將使用者的變數顯示到螢幕上,如果不是 one, two, three 時,就告知使用者僅有這三種選擇。
      [root@linux scripts]# vi sh11.sh
      #!/bin/bash
      # Program:
      #       Let user input one, two, three and show in screen.
      # History:
      # 2005/08/29    csie   First release
      
      echo "This program will print your selection !"
      # read -p "Input your choice: " choice
      # case $choice in
      case $1 in
        "one")
              echo "Your choice is ONE"
              ;;
        "two")
              echo "Your choice is TWO"
              ;;
        "three")
              echo "Your choice is THREE"
              ;;
        *)
              echo "Usage {one|two|three}"
              ;;
      esac
      
  • 利用 function 功能
    1. 語法:
      function fname() {
              程式段
      }
      
    2. 在 shell script 中,function 的設定一定要在程式的最前面,才能在執行時被找到可用的程式。改寫 sh11.sh:
      [root@linux scripts]# vi sh11-2.sh
      #!/bin/bash
      # Program:
      #       Let user input one, two, three and show in screen.
      # History:
      # 2005/08/29    csie   First release
      
      function printit(){
              echo -n "Your choice is "
      }
      
      echo "This program will print your selection !"
      case $1 in
        "one")
              printit; echo $1 | tr 'a-z' 'A-Z'
              ;;
        "two")
              printit; echo $1 | tr 'a-z' 'A-Z'
              ;;
        "three")
              printit; echo $1 | tr 'a-z' 'A-Z'
              ;;
        *)
              echo "Usage {one|two|three}"
              ;;
      esac
      
    3. function 也擁有內建變數:$0 代表函式名稱,後續接的變數以 $1, $2,... 取代。改寫上例:
      [root@linux scripts]# vi sh11-3.sh
      #!/bin/bash
      # Program:
      #       Let user input one, two, three and show in screen.
      # History:
      # 2005/08/29    csie   First release
      
      function printit(){
              echo "Your choice is $1"
      }
      
      echo "This program will print your selection !"
      case $1 in
        "one")
              printit 1
              ;;
        "two")
              printit 2
              ;;
        "three")
              printit 3
              ;;
        *)
              echo "Usage {one|two|three}"
              ;;
      esac
      

練習題

  1. 使用 if 語法,撰寫一 shell script,偵測輸入的參數是否為 hello。如果是,顯示 "Hello, how are you ?";如果沒有加任何參數,提示使用者必須要使用的參數下達法;而如果加入的參數不是 hello ,就提醒使用者僅能使用 hello 為參數。
    Sol.
    if [ "$1" == "hello" ]; then
            echo "Hello, how are you ?"
    elif [ "$1" == "" ]; then
            echo "You MUST input parameters, ex> $0 someword"
    else
            echo "The only parameter is 'hello'"
    fi
    

  2. 使用 case 語法,撰寫一 shell script,偵測輸入的參數是否為 hello。如果是,顯示 "Hello, how are you ?";如果沒有加任何參數,提示使用者必須要使用的參數下達法;而如果加入的參數不是 hello ,就提醒使用者僅能使用 hello 為參數。
    Sol.
    case $1 in
      "hello")
            echo "Hello, how are you ?"
            ;;
      "")
            echo "You MUST input parameters, ex> $0 someword"
            ;;
      *)
            echo "Usage $0 {hello}"
            ;;
    esac
    

  3. 撰寫一 shell script,透過 netstat 偵測主機是否有開啟 ftp 網路服務,其埠口為 21。
    Sol.
    testing=`netstat -tuln | grep ":21 "`
    if [ "$testing" != "" ]; then
            echo "FTP is running in your system."
    fi
    

  4. 撰寫一 shell script,讓使用者輸入畢業日期;再由現在日期比對畢業日期;由兩個日期的比較來顯示『還需要幾天』才能夠畢業的字樣。
    Sol.
    read -p "Please input your graduation date (YYYYMMDD ex>20050401): " date2
    
    date_d=`echo $date2 |grep '[0-9]\{8\}'`
    if [ "$date_d" == "" ]; then
            echo "You input the wrong format of date...."
            exit 1
    fi
    
    declare -i date_dem=`date --date="$date2" +%s`
    declare -i date_now=`date +%s`
    declare -i date_total_s=$(($date_dem-$date_now))
    declare -i date_d=$(($date_total_s/60/60/24))
    if [ "$date_total_s" -lt "0" ]; then
            echo "You had been graduation before: " $((-1*$date_d)) " ago"
    else
            declare -i date_h=$(($(($date_total_s-$date_d*60*60*24))/60/60))
            echo "You will be demobilized after $date_d days and $date_h hours."
    fi
    

  5. 使用 case 語法,撰寫一 shell script,讓使用者能夠輸入 one, two, three,並且將使用者的變數顯示到螢幕上,如果不是 one, two, three 時,就告知使用者僅有這三種選擇。
    Sol.
    case $1 in
      "one")
            echo "Your choice is ONE"
            ;;
      "two")
            echo "Your choice is TWO"
            ;;
      "three")
            echo "Your choice is THREE"
            ;;
      *)
            echo "Usage {one|two|three}"
            ;;
    esac
    

  6. 使用 function 功能及 case 語法,撰寫一 shell script,讓使用者能夠輸入 one, two, three,並且將使用者的變數顯示到螢幕上,如果不是 one, two, three 時,就告知使用者僅有這三種選擇。
    Sol.
    function printit(){
            echo -n "Your choice is "
    }
    case $1 in
      "one")
            printit; echo $1 | tr 'a-z' 'A-Z'
            ;;
      "two")
            printit; echo $1 | tr 'a-z' 'A-Z'
            ;;
      "three")
            printit; echo $1 | tr 'a-z' 'A-Z'
            ;;
      *)
            echo "Usage {one|two|three}"
            ;;
    esac
    

  7. 使用 function 與 變數 $1 功能及 case 語法,撰寫一 shell script,讓使用者能夠輸入 one, two, three,並且將使用者的變數顯示到螢幕上,如果不是 one, two, three 時,就告知使用者僅有這三種選擇。
    Sol.
    function printit(){
            echo "Your choice is $1"
    }
    case $1 in
      "one")
            printit 1
            ;;
      "two")
            printit 2
            ;;
      "three")
            printit 3
            ;;
      *)
            echo "Usage {one|two|three}"
            ;;
    esac
    


next up previous contents
Next: 迴圈 (loop) Up: Shell scripts - 條件判斷與迴圈 Previous: Shell scripts - 條件判斷與迴圈   Contents
2017-06-14