Shell 流程式控制制-if 語句

來源:互聯網
上載者:User

標籤:

  1. 單分支if條件陳述式

    if [ 條件判斷式 ] ; then
    程式
    fi

    例子:判斷分區使用率

    #!/bin/bash# Author: huangrui (Email:[email protected]) rate=$(df -h | grep "sda1" | awk ‘{print $5}‘ | cut -f 1 -d "%") if [ $rate -gt 80 ]; then   echo "Warning! disk is full !!!"fi
    Code
  2. 雙分支if條件陳述式
    if [ 條件判斷式 ] ; then
    條件執行成立時,執行的語句
    else
    條件執行不成立,執行的語句
    fi

    例子:備份網站目錄檔案

    #!/bin/bash# Author huangrui (Email:[email protected]) date=$(date +%y%m%d)size=$(du -sh /home/test.com) if [ -d /home/test.com ];then    echo "date is :$date" > /tmp/dbback/db.txt    echo "size is :$size" >> /tmp/dbback/db.txt    cd /tmp/dbback    tar -zcf web_$date.tar.gz /home/test.com db.txt&>/dev/null    rm -rf /tmp/dbback/db.txtelse    mkdir /tmp/dbback    echo "date is :$date" > /tmp/dbback/db.txt    echo "size is :$size" >> /tmp/dbback/db.txt    cd /tmp/dbback    tar -zcf web_$date.tar.gz /home/test.com db.txt&>/dev/null    rm -rf /tmp/dbback/db.txtfi
    Code

    判斷apache是否啟動,使用nmap命令

    #!/bin/bash# Author huangrui (Email:[email protected]) port=$(nmap -sT 172.16.193.128 | grep tcp | grep http | awk ‘{print $2}‘) if [ "$port" == "open" ]; then   echo "$(date) httpd is ok!" >> /tmp/autostart-acc.logelse   /etc/rc.d/init.d/httpd restart &>/dev/null   echo "$(date) httpd is restart!!" >> /tmp/autostart-err.logfi
    Code
  3. 多分支if條件陳述式
    if [ 條件判斷1 ]; then
    當條件判斷式1成立時,執行程式1
    elif [ 條件判斷式2 ]; then
    當條件判斷式2成立時,執行程式2
    …省略更多條件…
    else
    當所有條件都不成立,最後執行此程式
    fi

Shell 流程式控制制-if 語句

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.