Shell筆記:if和case條件判斷

1、if語句bash

 單分支if語句服務器

語法(中括號首尾的空格不能省略):tcp

if [ 條件判斷式 ];then
    程序
fi
#或者
if [ 條件判斷式 ]
    then
        程序
fi

 

示例:spa

#!/bin/bash

#根分區的使用率若是達到80則發出警告,向屏幕輸出一條提示信息。
rate=$(df -h | grep /dev/sda5 | awk '{print $5}' | cut -d "%" -f 1)

if [ $rate -ge 80 ]
    then
        echo "/dev/sda5 is full!!!"
fi

 

 

雙分支if語句rest

語法:code

if [ 條件判斷式 ]
    then
        程序1
    else
        程序2
fi

 

示例1:對數據進行備份blog

#!/bin/bash
#獲取當前系統時間,並以年月日的格式顯示
date=$(date +%y%m%d)
#獲取目錄/etc的大小
size=$(du -sh /etc)

#若是存在目錄
if [ -d /tmp/dbback ]
    then
        echo "Date is: $date" > tmp/dbback/db.txt
        echo "Size is: $size" >> /tmp/dbback/db.txt
        #在腳本中也是可使用cd這樣的命令的
        cd /tmp/dbback
        #打包壓縮文件進行備份,而且將命令執行後的信息丟棄
        tar -zcf etc_$date.tar.gz /etc db.txt &>/dev/null
        rm -rf /tmp/dbback/db.txt
    else
        mkdir /tmp/dbback
        echo "Date is: $date" > tmp/dbback/db.txt
        echo "Size is: $size" >> /tmp/dbback/db.txt
        cd /tmp/dbback
        tar -zcf etc_$date.tar.gz /etc db.txt &>/dev/null
        rm -rf /tmp/dbback/db.txt
fi

 

示例2:檢查某個服務是否正常運行input

#!/bin/bash
port=$(nmap -sT 192.168.1.159 | grep tcp | grep http | awk '{print $2}')
#使用nmap命令掃描服務器,並截取Apache服務的狀態
if [ "$port"=="open" ]
    then
        echo "$(date) httpd is ok!" >> /tmp/autostart-acc.log
    else
        #重啓Apache服務
        /etc/rc.d/init.d/httpd start $>/dev/null
        echo "$(date) restart httpd!!" >> /tmp/autostart-err.log
fi

 

 

多分支if語句it

語法:class

if [ 條件判斷式1 ]
    then
        程序1
elif [ 條件判斷式2 ]
    then
        程序2
...
else
    程序n
fi

 

示例:

#!/bin/bash

# 從鍵盤輸入讀取值並賦予變量file
read -p "Please input a filename: " file

#判斷變量file是否爲空
if [ -z "$file" ]
    then
        echo "Error, ase input a filename!"
        #退出並設置返回碼
        exit 1
#判斷文件是否存在
elif [ ! -e "$file" ]
    then
        echo "Error, your input is not a file!"
        exit 2
#判斷file的值是否爲普通文件
elif [ -f "$file" ] 
    then
        echo "$file is a regulare file!"
#判斷file的值是否爲目錄文件
elif [ -d "$file" ]
    then
        echo "$file is a directory!"
else
    echo "$file is an other file!"
fi

 

 

2、case語句

語法:

case $變量名 in
    "值1")
        程序1
        ;;
    "值2")
        程序2
        ;;
    ...
    *)
        程序n
        ;;
esac

 

示例:

#!/bin/bash

read -p "Please choose yes/no: " -t 30 cho
case $cho in
    "yes")
        echo "Your choose is yes!"
        ;;
    "no")
        echo "Your choose is no!"
        ;;
    *)
        echo "Your choose is error!"
        ;;
esac
相關文章
相關標籤/搜索